PageRenderTime 17ms CodeModel.GetById 12ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

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