2019独角兽企业重金招聘Python工程师标准>>>
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 blocke.printStackTrace();}}
}
class ReadPipe implements Runnable{PipedReader read=new PipedReader();public PipedReader getRead(){return read;}@Overridepublic 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;}@Overridepublic 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}}
}