Use pipelines for input and output between tasks

Source: Internet
Author: User

Content: Communication between threads via input/output is often useful. Take advantage of the PipedWriter class (which allows tasks to be written to the pipeline) and the Pipedreader class (allowing different tasks to be read from the same pipeline). In the code below, sender and receiver represent two tasks that need to communicate with each other. Sender puts the data in writer and then sleeps for a while. However, receiver does not have sleep () and wait (). But when he calls read (), if there is no more data, the pipeline will block, and normal I/O cannot be interrupted.

Class Sender implements Runnable {private Random rand = new random;p rivate pipedwriter out = new PipedWriter ();p ublic PipedWriter Getpipedwriter () {return out;} @Overridepublic void Run () {try {while (true) {for (char c = ' A '; c <= ' z '; C + +) {Out.write (c); TimeUnit.MILLISECONDS.sleep (Rand.nextint (500));}}} catch (IOException e) {System.out.println (e + "Sender write exception"),} catch (Interruptedexception e) {System.out.prin TLN (e + "Sender Sleeo Interrupted");}} Class Receiver implements Runnable {private pipedreader in;public Receiver (sender sender) throws IOException {in = new Pip Edreader (Sender.getpipedwriter ());} @Overridepublic void Run () {try {while (true) {System.out.println ("Read:" + (char) in.read () + ".");}} catch (IOException e) {System.out.println (e + "Receiver read exception");}}} public class Pipedio {public static void main (string[] args) throws Exception {Sender sender = new sender (); Receiver receiver = new Receiver (sender); Executorservice exec = EXECUTORS.NEWCACHedthreadpool (); Exec.execute (sender); Exec.execute (receiver); TimeUnit.SECONDS.sleep (4); Exec.shutdownnow ();}}


Use pipelines for input and output between tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.