Detailed explanation of pipeline communication in Java multithreaded programming
The previous chapter talked about wait / notify communication. In this section, we will discuss the use of pipes for communication.
Java provides IO stream, which makes it convenient for us to operate data. Pipestream is a special stream used to directly transfer data between different threads. One thread sends data to the output pipe, and another thread reads data from the input pipe. Communication through pipelines does not require things like temporary files.
Java provides four classes to enable communication between threads:
① Byte stream: pipeinputstream, pipedoutputstream ② character stream: pipedreader, pipedwriter
Let's look at the implementation method of byte stream:
Console output:
read: write: 123456789101112131415161718192021... 123456789101112131415161718192021...
In the above test, the input thread is started first, and then because no thread is written, the thread is blocked until data is written.
Let's continue to look at the implementation method of character stream:
The character stream is similar to the byte stream. In the above example, the character stream does not need to create a byte array.
The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.