9.线程间通信:管道

2018-07-10  本文已影响0人  xialedoucaicai

管道流是一种特殊的流,可以在不同线程之间传递数据。一个线程发送数据到输出管道,另一个线程从输入管道读取数据,而无需借用临时文件。

管道流包含这四个类:
字节流
PipedInputStream
PipedOutputStream
字符流
PipedReader
PipedWriter

具体使用和普通的流一样,唯一不同的是,需要把输入流和输出流连接起来。看一个字节流的代码示例,还是比较简单的。
输入流

public class PipedByteInput {
    PipedInputStream pipedInputStream = null;
    
    public PipedByteInput(PipedInputStream pipedInputStream) {
        this.pipedInputStream = pipedInputStream;
    }
    
    public void readData() throws Exception{
        byte [] b = new byte[20];
        int eof = 0;
        StringBuilder result = new StringBuilder("");
        try{
            while((eof =pipedInputStream.read(b))!=-1){
                result.append(new String(b,0,eof));
            }
        }finally{
            pipedInputStream.close();
        }
        System.out.println("读取到的数据:"+result);
    }
}

输入流线程

public class ReadThread extends Thread{
    PipedByteInput pipedByteInput = null;
    
    public ReadThread(PipedByteInput pipedByteInput) {
        this.pipedByteInput = pipedByteInput;
    }
    
    @Override
    public void run() {
        try {
            pipedByteInput.readData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出流

public class PipedByteOutput {
    PipedOutputStream pipedOutputStream = null;
    
    public PipedByteOutput(PipedOutputStream pipedOutputStream) {
        this.pipedOutputStream = pipedOutputStream;
    }
    
    public void writeData(String text) throws Exception{
        try{
            pipedOutputStream.write(text.getBytes());   
        }finally{
            pipedOutputStream.close();  
        }
    }
}

输出流线程

public class WriteThread extends Thread{
    PipedByteOutput pipedByteOutput = null;
    public WriteThread(PipedByteOutput pipedByteOutput) {
        this.pipedByteOutput = pipedByteOutput;
    }
    @Override
    public void run() {
        try {
            pipedByteOutput.writeData("PipedByteOutput write data..");  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Main

public class Main {
    public static void main(String[] args) throws InterruptedException, IOException {
        PipedInputStream pis = new PipedInputStream();
        PipedOutputStream pos = new PipedOutputStream();
        //将管道输入流和输出流关联起来
        pis.connect(pos);
        
        PipedByteInput read = new PipedByteInput(pis);
        PipedByteOutput write = new PipedByteOutput(pos);
        
        ReadThread readThread = new ReadThread(read);
        WriteThread writeThread = new WriteThread(write);
        
        readThread.start();
        Thread.sleep(2000);
        writeThread.start();
    }
}
上一篇 下一篇

猜你喜欢

热点阅读