/examples/kilim/examples/Chain.java

http://github.com/kilim/kilim · Java · 57 lines · 33 code · 5 blank · 19 comment · 5 complexity · efe523516c82e0c334820e00e05c18b8 MD5 · raw file

  1. /* Copyright (c) 2006, Sriram Srinivasan
  2. *
  3. * You may distribute this software under the terms of the license
  4. * specified in the file "License"
  5. */
  6. package kilim.examples;
  7. import kilim.*;
  8. /**
  9. * Set up a chain of tasks. Each task knows about its mailbox and
  10. * that of the next in the chain, but is not given the other tasks
  11. * ref.
  12. * The main thread pushes an empty StringBuffer into the first task's
  13. * mailbox, which writes "hello" into the buffer and passes the
  14. * modified StringBuffer on to the next task, and so on. The last
  15. * task appends "world", prints it out and exits.
  16. *
  17. * [compile] javac -d ./classes Chain.java
  18. * [weave] java kilim.tools.Weave -d ./wclasses kilim.examples.Chain
  19. * [run] java -cp ./wclasses:./classes:$CLASSPATH kilim.examples.Chain
  20. * @author ram
  21. */
  22. public class Chain extends Task {
  23. Mailbox<StringBuffer> mymb, nextmb;
  24. public Chain(Mailbox<StringBuffer> mb, Mailbox<StringBuffer> next) {
  25. mymb = mb;
  26. nextmb = next;
  27. }
  28. public void execute() throws Pausable{
  29. while(true) {
  30. StringBuffer sb = mymb.get();
  31. if (nextmb == null) {
  32. System.out.print(sb);
  33. System.out.println("world");
  34. System.exit(0);
  35. } else {
  36. sb.append("hello ");
  37. nextmb.put(sb);
  38. }
  39. }
  40. }
  41. public static void main(String args[]) {
  42. int n = args.length == 0 ? 10 : Integer.parseInt(args[0]);
  43. Mailbox<StringBuffer> mb = new Mailbox<StringBuffer>();
  44. Mailbox<StringBuffer> nextms = null;
  45. for (int i = 0; i < n; i++) {
  46. new Chain(mb, nextms).start();
  47. nextms = mb;
  48. mb = new Mailbox<StringBuffer>();
  49. }
  50. nextms.putnb(new StringBuffer());
  51. }
  52. }