Readers Writers  «Prev  Next»


Lesson 8Piped readers and writers
ObjectiveInvestigate how to connect writers to readers for interthread communication.

Piped Readers and Writers | Inter-thread Communication

Piped readers and writers do for character streams what piped input and output streams do for byte streams. They allow two threads to communicate. Output from one thread becomes input for the other thread.
Piped readers and writers are normally created in pairs. The piped writer becomes the underlying source for the piped reader. This is one of the few cases where a reader does not have an underlying input stream.

Here is an example of creating a piped reader and a piped writer:
PipedWriter pw = new PipedWriter();
PipedReader pr = new PipedReader(pw);

This simple example is a little deceptive because these lines of code will normally be in different methods, and perhaps even different classes. Some mechanism must be established to pass a reference to the PipedOutputStream into the thread that handles the PipedInputStream. Or you can create them in the same thread; then pass a reference to the connected stream into a separate thread.
Alternatively, you can reverse this:

PipedReader pr = new PipedReader();
PipedWriter pw = new PipedWriter(pr);
Or you can create them both unconnected, then use one or the other's connect() method to link them:
PipedReader pr = new PipedReader();
PipedWriter pw = new PipedWriter();
pr.connect(pw);

Otherwise, these classes just have the usual read(), write(), flush(), close(), and available() methods like all Reader and Writer classes.