Java Reference
In-Depth Information
typically, a pipe is used to transfer data from one thread to another. One thread will produce data and another
thread will consume the data. note that the synchronization between two threads is taken care of by the blocking read
and write.
Tip
Listing 7-20 demonstrates how to use a piped I/O. The main() method creates and connects a piped input and
a piped output stream. The piped output stream is passed to the produceData() method, producing numbers from 1
to 50. The thread sleeps for a half second after producing a number. The consumeData() method reads data from the
piped input stream. I used a quick and dirty way of handling the exceptions to keep the code smaller and readable.
Data is produced and read in two separate threads.
Listing 7-20. Using Piped Input and Output Streams
// PipedStreamTest.java
package com.jdojo.io;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStreamTest {
public static void main(String[] args) throws Exception {
// Create and connect piped input and output streams
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
pos.connect(pis);
// Creates and starts two threads, one to produce data (write data)
// and one to consume data (read data)
Runnable producer = () -> produceData(pos);
Runnable consumer = () -> consumeData(pis);
new Thread(producer).start();
new Thread(consumer).start();
}
public static void produceData(PipedOutputStream pos) {
try {
for (int i = 1; i <= 50; i++) {
pos.write((byte) i);
pos.flush();
System.out.println("Writing: " + i);
Thread.sleep(500);
}
pos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
 
 
Search WWH ::




Custom Search