一個線程發送數據到輸出管道,另外一個線程從輸入管道中讀取數據。經過使用管道,實現不一樣線程間的通訊,而無須藉助於相似臨時文件之類的東西。
在java的jdk中提供了4個類來使線程間能夠進行通訊:
PipedInputStream 和 PipedOutputStream
PipedReader 和 PipedWriter java
public static class ReadClient implements Runnable{ private PipedInputStream reader; public ReadClient(PipedInputStream reader) { this.reader = reader; } @Override public void run() { byte[] bytes = new byte[50]; try { do { int readLength = reader.read(bytes);//方法會一直阻塞,直到有數據被寫入 if(readLength==-1){continue;} String message = new String(bytes,0,readLength); System.out.println("get: "+message); }while(true); } catch (IOException e) { //something }finally{ try { reader.close(); } catch (IOException e) { //something } } } } public static class WriteClient implements Runnable{ private PipedOutputStream writer; public WriteClient(PipedOutputStream writer) { this.writer = writer; } @Override public void run() { int seed = 0; try { while (true) { seed++; String message = ""+seed; System.out.println("send: "+seed); writer.write(message.getBytes()); writer.flush(); Thread.sleep(1000); } } catch (InterruptedException | IOException e) { //something }finally{ try { writer.close(); } catch (IOException e) { //something } } } } public static void main(String[] args) throws InterruptedException, IOException { PipedInputStream inputStream = new PipedInputStream(); PipedOutputStream outputStream = new PipedOutputStream(); //管道鏈接 inputStream.connect(outputStream); //或 outputStream.connect(inputStream); //建立讀寫線程 Thread reader = new Thread(new ReadClient(inputStream)); reader.start(); Thread.sleep(2000); Thread writer = new Thread(new WriteClient(outputStream)); writer.start(); }
結果:
send: 1
get: 1
send: 2
get: 2
send: 3
get: 3
ide