Java multi-threaded - pipe flow to achieve inter-thread communication

Pipeline flow

In the Java language provides a variety of input / output stream Stream, allows us to easily manipulate the data, which is a special pipeline flow stream, for transferring data directly between different threads. A thread sending data to the output pipe flow, another thread to read data from the input stream conduit.

By using pipes for communication between different threads, without resorting to things like similar temporary files.

Byte stream

PipedInputStream sum PipedOutputStream

Character stream

PipedReader 和 PipedWriter

 

Example:

public class PipeStreamTest {
    public static void main(String[] args) throws IOException, InterruptedException {
        WriteData writeData = new WriteData();
        ReadData readData = new ReadData();

        PipedReader reader = new PipedReader();
        PipedWriter writer = new PipedWriter();

        writer.connect(reader);

        new Thread(() -> {
            writeData.writeMethod(writer);
        }).start();

        Thread.sleep(2000);

        new Thread(() -> {
            readData.readMethod(reader);
        }).start();
    }

    static class WriteData {
        public void writeMethod(PipedWriter writer) {
            try {
                System.out.println("write :");
                for (int i = 0; i < 300; i++) {
                    String outData = "" + (i + 1);
                    writer.write(outData);
                    System.out.print(outData);
                }
                System.out.println();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    static class ReadData {
        public void readMethod(PipedReader reader) {
            try {
                System.out.println("read :");
                char[] byteArray = new char[20];
                int readLength = reader.read(byteArray);
                while (readLength != -1) {
                    String newData = new String(byteArray, 0, readLength);
                    System.out.print(newData);
                    readLength = reader.read(byteArray);
                }
                System.out.println();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Results are as follows:

 

Guess you like

Origin www.cnblogs.com/lkc9/p/12528466.html