【2013-12-16】《Java编程思想》读书笔记:Pipe

【2013-12-16】《Java编程思想》读书笔记:Pipe

[历史归档]本文原发布于 cstriker1407.info 个人博客,内容为历史存档,仅供参考。
发布时间:2013-12-16| 标题:《Java编程思想》读书笔记:Pipe分类:编程 / java / think_in_java |标签:java·think in java·多线程·pipe


《Java编程思想》读书笔记:Pipe

最近在整理 Java 的多线程相关的技术,这里备份下关于【 Pipe 】代码。

github:

【 https://github.com/cstriker1407/think_in_java 】

备注:

参考链接:

【 http://www.cnblogs.com/king1302217/p/3158842.html 】

【 http://ifeve.com/pipe/ 】

java代码:

publicclassPipedStreamTest{publicstaticvoidtest(){PipedOutputStreampos=newPipedOutputStream();PipedInputStreampis=newPipedInputStream();try{pos.connect(pis);}catch(IOExceptione){e.printStackTrace();}PipedOutThreadout=newPipedOutThread(pos);PipedInThreadin=newPipedInThread(pis);out.start();in.start();}}classPipedOutThreadextendsThread{PipedOutputStreampos;publicPipedOutThread(PipedOutputStreampos){this.pos=pos;}@Overridepublicvoidrun(){for(inti=0;i<10;i++){try{System.out.println("写入:"+i);pos.write(i);}catch(IOExceptione1){e1.printStackTrace();}try{Thread.sleep(newRandom().nextInt(100));}catch(InterruptedExceptione){e.printStackTrace();}}}}classPipedInThreadextendsThread{PipedInputStreampin;publicPipedInThread(PipedInputStreampin){this.pin=pin;}@Overridepublicvoidrun(){for(inti=0;i<10;i++){try{Thread.sleep(newRandom().nextInt(100));}catch(InterruptedExceptione){e.printStackTrace();}try{intx=pin.read();System.out.println("读取:"+x);}catch(IOExceptione){e.printStackTrace();}}}}

日志打印:

写入:0 读取:0 写入:1 写入:2 写入:3 读取:1 读取:2 读取:3 写入:4 写入:5 写入:6 写入:7 写入:8 写入:9 读取:4 读取:5 读取:6 读取:7 读取:8 读取:9