KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test > utils > ConsumerPipe


1 package test.utils;
2
3 import java.io.IOException JavaDoc;
4 import java.io.PipedInputStream JavaDoc;
5 import java.io.PipedOutputStream JavaDoc;
6
7 public class ConsumerPipe implements Runnable JavaDoc
8 {
9     PipedInputStream JavaDoc consumer = null;
10     String JavaDoc result;
11     private static int pipecount = 0; //thread counter for debuggers and stack traces.
12
boolean done = false;
13     
14     public ConsumerPipe(PipedOutputStream JavaDoc out) throws IOException JavaDoc {
15         consumer = new PipedInputStream JavaDoc(out);
16         pipecount++;
17     }
18     
19     public void run()
20     {
21         try
22         {
23             char[] chars = new char[consumer.available()];
24             for (int i =0; i < chars.length; i++)
25             {
26                 chars[i] = (char)consumer.read();
27             }
28             result = new String JavaDoc(chars);
29         }
30         catch (IOException JavaDoc ioe)
31         {
32             ioe.printStackTrace();
33         }
34         finally {
35             try {
36                 consumer.close();
37             }
38             catch (IOException JavaDoc e) {
39                 e.printStackTrace();
40             }
41             done = true;
42             synchronized (this) {
43                 notifyAll();
44             }
45         }
46     }
47
48     /**
49      * Starts this object as a thread, which results in the run() method being
50      * invoked and work being done.
51      */

52     public String JavaDoc getResult() {
53         Thread JavaDoc reader = new Thread JavaDoc(this, "Piper-"+pipecount);
54         reader.start();
55         while (!done) {
56             synchronized (this) {
57                 try {
58                     wait();
59                 } catch (InterruptedException JavaDoc e) {
60                 }
61             }
62         }
63         return result;
64     }
65 }
66
Popular Tags