【JAVA IO】_管道流筆記

來源:互聯網
上載者:User

【JAVA IO】_管道流筆記

本章目標:
掌握線程通訊流(管道流)的使用

管道流

管道流的主要作用是可以進行兩個線程間的通訊,分為管道輸出資料流(PipedOutputStream)、管道輸入資料流(PipedInputStream),如果要想進行管道輸出,則必須把輸出資料流連在輸入資料流之上,在PipedOutputStream類上有如下的一個方法用於串連管道。

public void connect(PipInputStream snk) throws IOException

要想實現管道流,則可以使用管道輸出資料流(PipedOutputStream)、管道輸入資料流(PipedInputStream)

import java.io.* ;class Send implements Runnable{            // 線程類    private PipedOutputStream pos = null ;    // 管道輸出資料流    public Send(){        this.pos = new PipedOutputStream() ;    // 執行個體化輸出資料流    }    public void run(){        String str = "Hello World!!!" ;    // 要輸出的內容        try{            this.pos.write(str.getBytes()) ;        }catch(IOException e){            e.printStackTrace() ;        }        try{            this.pos.close() ;        }catch(IOException e){            e.printStackTrace() ;        }    }    public PipedOutputStream getPos(){    // 得到此線程的管道輸出資料流        return this.pos ;        }};class Receive implements Runnable{    private PipedInputStream pis = null ;    // 管道輸入資料流    public Receive(){        this.pis = new PipedInputStream() ;    // 執行個體化輸入資料流    }    public void run(){        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)) ;    }    public PipedInputStream getPis(){        return this.pis ;    }};public class PipedDemo{    public static void main(String args[]){        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() ;    // 啟動線程    }};

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.