1.管道输入/输出流类
分为两类,字节流管道类(PipedInputStream/PipedOutputStream)和字符流管道类(PipedReader/ PipedWriter)。这两个IO流实现了可以在不同的任务中对同一个管道进行读写操作,这个模型可以看成是“生产者消-费者模式”的变体,管道是一个阻塞队列。
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PipedReader;
import java.io.PipedWriter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class PipeIO {
public static void main(String[] args) {
ReadPipe read=new ReadPipe();
WritePipe write=new WritePipe();
ExecutorService exec=Executors.newCachedThreadPool();
try {
write.getWriter().connect(read.getRead());;//必须将两个管道进行连接,然后才可进行线程间的数据交互
exec.execute(read);
exec.execute(write);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ReadPipe implements Runnable{
PipedReader read=new PipedReader();
public PipedReader getRead(){
return read;
}
@Override
public void run() {
try {
while(true){
System.out.println("read:"+(char)read.read()+";");//当前线程从管道读取数据
}
} catch (IOException e) {
// TODO: handle exception
}
}
}
class WritePipe implements Runnable{
PipedWriter writer=new PipedWriter();
public PipedWriter getWriter(){
return writer;
}
@Override
public void run() {
try {
while(true){
for(char a='A';a<='z';a++){
writer.write(a);//当前线程向管道输出数据
TimeUnit.SECONDS.sleep(2);
}
}
} catch (IOException e) {
// TODO: handle exception
}catch (InterruptedException e) {
// TODO: handle exception
}
}
}