Flow conduit for communication between threads

Pipeline flow (PipedInputStream, PipedOutputStream) inherited from inputStream, inter-thread communication general users, but most do not use it. .

. .
Test Case

The sender thread creation

class SendThread implements Runnable{
    private PipedOutputStream outputStream = new PipedOutputStream();
    @Override
    public void run() {
        try {
            outputStream.write("管道对接成功!!".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public PipedOutputStream getOutputStream() {
        return outputStream;
    }
    public void setOutputStream(PipedOutputStream outputStream) {
        this.outputStream = outputStream;
    }
}

The recipient thread creation

class RecieveThread implements Runnable{
    private PipedInputStream inputStream = new PipedInputStream();
    @Override
    public void run() {
        byte[] data = new byte[1024];
        try {
            int len = inputStream.read(data);
            System.out.println("对接情况:"+new String(data,0,len));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PipedInputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(PipedInputStream inputStream) {
        this.inputStream = inputStream;
    }
}

test

public class GuandaoTest {
    public static void main(String[] args) {
        SendThread sendThread = new SendThread();
        RecieveThread recieveThread = new RecieveThread();
        PipedOutputStream outputStream = sendThread.getOutputStream();
        try {
            outputStream.connect(recieveThread.getInputStream());
            new Thread(sendThread).start();
            new Thread(recieveThread).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

analysis

In the pipe flow has entered the recipient, the sender outputs a duct stream, the client acquires the output stream, the input stream to its butt, corresponds to the pipe is turned, then the received information of the input stream to the output stream.

Published 47 original articles · won praise 6 · views 2188

Guess you like

Origin blog.csdn.net/weixin_44467251/article/details/103091919