最近在整理 Java 的多线程相关的技术,这里备份下关于【 Pipe 】代码。
github:
【 https://github.com/cstriker1407/think_in_java 】
备注:
参考链接:
【 http://www.cnblogs.com/king1302217/p/3158842.html 】
java代码:
public class PipedStreamTest { public static void test() { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(); try { pos.connect(pis); } catch (IOException e) { e.printStackTrace(); } PipedOutThread out = new PipedOutThread(pos); PipedInThread in = new PipedInThread(pis); out.start(); in.start(); } } class PipedOutThread extends Thread { PipedOutputStream pos; public PipedOutThread(PipedOutputStream pos) { this.pos = pos; } @Override public void run() { for (int i = 0; i < 10; i++) { try { System.out.println("写入:" + i); pos.write(i); } catch (IOException e1) { e1.printStackTrace(); } try { Thread.sleep(new Random().nextInt(100)); } catch (InterruptedException e) { e.printStackTrace(); } } } } class PipedInThread extends Thread { PipedInputStream pin; public PipedInThread(PipedInputStream pin) { this.pin = pin; } @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(new Random().nextInt(100)); } catch (InterruptedException e) { e.printStackTrace(); } try { int x = pin.read(); System.out.println("读取:" + x); } catch (IOException e) { e.printStackTrace(); } } } }
日志打印:
写入:0 读取:0 写入:1 写入:2 写入:3 读取:1 读取:2 读取:3 写入:4 写入:5 写入:6 写入:7 写入:8 写入:9 读取:4 读取:5 读取:6 读取:7 读取:8 读取:9
发表评论