Piped streams are typically used in separate threads. One thread writes output to a PipedOutputStream. The other thread reads the same data from a PipedInputStream. The two streams are connected either through their constructors or through an explicit connect() method. To find out how to instantiate piped streams, see the tips "
Connecting the Piped Stream Classes" and "
Using Piped Streams in an Application."
You can use the piped streams in two dependent threads in a single class. This class creates two piped streams and connects them through the constructor in Lines 1-2. Lines 4-5 construct two threads with these streams as a parameter to each of them. The thread inThread will read in the data from the pins and the thread outThread will write the data to pouts. Lines 7-8 start the threads.
1. private PipedInputStream pins = new PipedInputStream();
2. private PipedOutputStream pouts = new PipedOutputStream(pins);
3.
4. Thread inThread = new PipedInputThread(pins);
5. Thread outThread = new PipedOutputThread(pouts);
6.
7. inThread.start();
8. outThread.start();
The code for the run() methods for the two threads is given in the tip "
Running Piped Threads." However, the classes are defined here. The class PipedInputThread is as follows:
1. class PipedInputThread extends Thread {
2. InputStream in_ = null;
3.
4. public PipedInputThread (InputStream in) { in_ = in; }
5. public void run () {
6. // Code that reads in from the PipedInputStream "in_"
7. }
8. }
The code for the class PipedOutputThread is similar:
1. class PipedOutputThread extends Thread {
2. OutputStream out_ = null;
3.
4. public PipedOutputThread (OutputStream out) { out_ = out; }
5. public void run ()
6. // Code that writes out to the PipedOutputStream "out_"
7. }
8. }