管道流的主要做用是能夠進行兩個線程間的通訊java
分爲管道輸出流(PipedOutputStream)和管道輸入流(PipedInputStream)ide
定義兩個線程對象,在發送的線程類中定義了管道輸出類,在接收的線程類中定義了管道的輸入類,在操做時只須要使用PipedOutputStream類中提供的connection()方法就能夠將兩個線程冠帶鏈接在一塊兒,線程啓動後會自動進行管道的輸入和輸出操做this
import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; //================================================= // File Name : Pipe_demo //------------------------------------------------------------------------------ // Author : Common // 類名:Send // 屬性: // 方法: class Send implements Runnable{ //實現Runnable接口 private PipedOutputStream pos = null; //管道輸出流 public Send() { //實例化輸出流 super(); this.pos = new PipedOutputStream(); } public PipedOutputStream getPos() { //經過線程類獲得輸出流 return pos; } @Override public void run() { // TODO 自動生成的方法存根 String str = "HelloWord!!"; try{ this.pos.write(str.getBytes()); //輸出信息 }catch(IOException e){ e.printStackTrace(); } try{ this.pos.close(); //關閉輸出流 }catch(IOException e){ e.printStackTrace(); } } } //類名:Receive //屬性: //方法: class Receive implements Runnable{ //實現Runnable接口 private PipedInputStream pis = null; //管道輸入流 public Receive() { //實例化輸出流 super(); this.pis = new PipedInputStream(); } public PipedInputStream getPis() { //經過線程類獲得輸入流 return pis; } @Override public void run() { // TODO 自動生成的方法存根 byte b[] = new byte[1024]; //實例化輸入流 int len = 0; try{ len = this.pis.read(b); //接收數據 }catch(IOException e){ e.printStackTrace(); } try{ this.pis.close(); //關閉輸入流 }catch(IOException e){ e.printStackTrace(); } System.out.println("接收的內容爲"+new String(b,0,len)); } } //主類 //Function : Pipe_demo public class Pipe_demo { public static void main(String[] args) { // TODO 自動生成的方法存根 Send s = new Send(); Receive r = new Receive(); try{ s.getPos().connect(r.getPis()); //鏈接管道 }catch(IOException e){ e.printStackTrace(); } new Thread(s).start(); new Thread(r).start(); } }