管道通訊,使用管道通訊進行資料交流(PipeInputStream)
阿新 • • 發佈:2018-12-12
想了解一下,管道之間是怎樣進行通訊的,於是看到網上的做的一個Demo,於是記錄下來,方便學習
寫一個訊息生產者
/** * @author chenxihua * @Date 2018年9月17日 * * 我們以數字替代產品 生產者每5秒提供5個產品,放入管道 */ public class MyProducer extends Thread { private PipedOutputStream outputStream; public MyProducer(PipedOutputStream outputStream) { this.outputStream = outputStream; } @Override public void run() { while (true) { try { for (int i = 0; i < 5; i++) { outputStream.write(i); } } catch (IOException e) { e.printStackTrace(); } try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
寫一個訊息消費者
/** * @author chenxihua * @Date 2018年9月17日 * * 消費者每0.5秒從管道中取1件產品,並列印剩餘產品數量,並列印產品資訊(以數字替代) */ public class MyConsumer extends Thread { private PipedInputStream inputStream; public MyConsumer(PipedInputStream inputStream) { this.inputStream = inputStream; } @Override public void run() { while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } try { int count = inputStream.available(); if (count > 0) { System.out.println("rest product count: " + count); System.out.println("get product: " + inputStream.read()); } } catch (IOException e1) { e1.printStackTrace(); } } } }
然後寫一個測試例項:
/** * @author chenxihua * @Date 2018年9月17日 */ public class PipeTest { public static void main(String[] args) { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(); try { pis.connect(pos); } catch (IOException e) { e.printStackTrace(); } new MyProducer(pos).start(); new MyConsumer(pis).start(); } }
嗯,到這裡應該沒問題了,管道之間的通訊,最主要的還是connect()方法,它是連結資料輸入與資料輸出的方法。