Java Reference
In-Depth Information
Sidebar 10.2 Pipe communication
Java Pipe is a mechanism for thread communication. A pipe is a unidirectional
channel that connects two threads. One thread writes streams of data into the
pipe and the other thread reads them. The pipe has a buffer that stores data until
a thread reads them. Reading operations are blocking. When a thread wants to
read data from the pipe, it suspends its execution if the pipe is empty and resumes
its execution when another thread writes new data into the pipe. Thus, the pipe
mechanism can be used for thread synchronization. The code below implements
a simple application that uses the pipe mechanism. An instance of class
Writer
sends an integer value through the pipe. An instance of class
Reader
waits for an
integer value from the pipe. Both classes,
Writer
and
Reader
, implement the
Runnable
interface. Class
Communication
creates the input and output ends of the
pipe and initializes the writer and reader threads.
import
java.io.*;
public class
Writer
implements
Runnable {
PipeOutputStream output;
int
counter
#
0;
public
Writer(PipeOutputStream o) {
this
.output
#
o; }
public void
run() {
while
(
true
)
try
{
counter
!!
;
System.out.println("Sending "
!
counter);
output.write(counter);
Thread.sleep(Math.round(Math.random()*2000.0
!
500.0));
}
catch
(Exception e) {}
} }
public class
Reader
implements
Runnable {
PipeInputStream input;
public
Reader(PipeInputStream i) {
this
.input
#
i; }
public void
run() {
while
(
true
)
try
{
int
value
#
(
int
) input.read();
System.out.println("Receiving "
!
value);
Thread.sleep(Math.round(Math.random()*2000.0
!
500.0));
}
catch
(Exception e) {}
} }
public class
Communication {
public static void
main(String[] args)
throws
Exception {
PipeInputStream input
#
new
PipeInputStream();
PipeOutputStream output
#
new
PipeOutputStream(input);
Thread writer
#
new
Thread(
new
Writer(output));
Thread reader
#
new
Thread(
new
Reader(input));
writer.start();
reader.start();
} }