7、IO--管道流
管道流可以實現兩個線程之間的通信
兩個線程:管道輸出流(PipedOutputStream)、管道輸入流(PipedInputStream)
?
如果要進行管道輸出,必須把輸出流連在輸入流之上
?
PipedOutputStream中的方法可以實現連接管道功能
public void connect(PipedInputStream snk) throws IOException
?
定義管道輸出流(寫數據的程序)
class Send implements Runnable{//管道輸出流PipedOutputStream pos = null;public Send(){//實例化管道輸出流this.pos = new PipedOutputStream();}@Overridepublic void run() {//要輸出的內容String str = "hello 世界!";try {this.pos.write(str.getBytes());} catch (Exception e) {e.printStackTrace();}try {this.pos.close();} catch (Exception e) {// TODO: handle exception }}//得到此線程的管道輸出流public PipedOutputStream getPos(){return this.pos;} }?
定義管道輸入流(取數據的程序)
class Receive implements Runnable{//管道輸入流private PipedInputStream pis = null;public Receive(){//實例化管道輸入流this.pis = new PipedInputStream();}@Overridepublic void run() {//接收內容byte b [] = new byte[1024];int len =0;try {//讀取內容len = this.pis.read(b);} catch (Exception e) {e.printStackTrace();}try {this.pis.close();} catch (Exception e) {e.printStackTrace();}//打印接收到的內容System.out.println("接收到內容:" + new String(b));}public PipedInputStream getPis(){return this.pis;} }?
測試類:
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();}?此時線程中可以進行打印結果
?
轉載于:https://www.cnblogs.com/Mrchengs/p/10816103.html
總結
- 上一篇: WinCE5.0如何安装.NET3.5
- 下一篇: 程序员写了段代码,自称完美! 网友: 我