Java thread Producer-consumers and queues, tasks using pipelines for input, output explanation example--thinking java4

Source: Internet
Author: User
Tags idn lenovo

Package Org.rui.thread.block2;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.blockingqueue;import Java.util.concurrent.linkedblockingqueue;import Java.util.concurrent.synchronousqueue;import org.rui.thread.liftoff;/** * Producer-Consumer and queue * * @author Lenovo * */class LiftOf Frunner implements Runnable {private blockingqueue<liftoff> rockets;public Liftoffrunner (blockingqueue< Liftoff> b) {rockets = B;} Add a task to the queue public void Add (LiftOff lo) {//To insert the specified element into this queue (if feasible immediately and without violating the capacity limit), try {rockets.put (lo);} catch ( Interruptedexception e) {e.printstacktrace ();}} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {//Gets and removes the head of this queue and waits (if necessary) until the element becomes available. LiftOff rocket = Rockets.take (); Rocket.run ();}} catch (Interruptedexception e) {System.out.println ("Break Exit"); SYSTEM.OUT.PRINTLN ("x exiting Liftoffrunner");}} public class Testblockingqueues {static void Getkey () {try {//CompenSate for Windows/linux difference in the//enter results in new BufferedReader (New InputStreamReader (system.in)). ReadLine (); catch (IOException e) {e.printstacktrace ();}} static void Getkey (String message) {SYSTEM.OUT.PRINTLN (message); Getkey ();} static void Tets (String msg, blockingqueue<liftoff> queue) {System.out.println (msg); Liftoffrunner runner = new Liftoffrunner (queue);//Start a thread, thread t = new Thread (runner), T.start (), for (int i = 0; i < 5; i++) {//Join task to Liftoffrunner queue Runner.add (new LiftOff (5));} Enter Console Getkey ("Press ' Enter ' (" + msg + ")"); T.interrupt (); System.out.println ("Finished" + msg + "Test");} public static void Main (string[] args) {tets ("Linkedblockingqueue", New Linkedblockingqueue<liftoff> ());// unlimited//sizetets ("Arrayblockingqueue", New Arrayblockingqueue<liftoff> (3));//fied//Sizetets (" Synchronousqueue ", New Synchronousqueue<liftoff> ());//Size of 1}}


Package Org.rui.thread.block2;import Java.util.random;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.linkedblockingqueue;import java.util.concurrent.timeunit;/** * Toast Blockingqueue * @author Lenovo * */class Toast {public enum Status {dry/* dry */, but tered/* butter */, jammed//jam}private Status status = Status.dry;private final int id;public Toast (int idn) {id = IDN;} public void butter () {status = status.buttered;} public void Jam () {status = status.jammed;} Public status GetStatus () {return status;} public int getId () {return ID;} Public String toString () {return "Toast" + ID + ":" + Status;}} /** * Toast Queue * * @author Lenovo * */class Toastqueue extends linkedblockingqueue<toast> {}class Toaster implements R unnable {private Toastqueue toastqueue;private int count = 0;private random rand = new Random ();p ublic Toaster (toastqueu E tq) {toastqueue = TQ;} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {TIMEUNIT.MIlliseconds.sleep (+ rand.nextint (500));//making toasttoast t = new Toast (count++); System.out.println (t);//INSERT INTO queuetoastqueue.put (t);}} catch (Interruptedexception e) {System.out.println ("Toaster Interrupted");} System.out.println ("toaster Off");}} Apply butter to Toastclass Butterer implements Runnable {private Toastqueue dryqueue, Butteredqueue;public butterer (Toa Stqueue dry, Toastqueue buttered) {dryqueue = Dry;butteredqueue = buttered;} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {//blocks until next piece of toast is available block until next loaf toast T = Dryqueue.take (); T.butter (); System.out.println (t); Butteredqueue.put (t);}} catch (Interruptedexception e) {System.out.println ("butter Interrupted");} System.out.println ("Apply butter Off");}} Apply jam to buttered Toastclass Jammer implements Runnable {private Toastqueue butteredqueue, Finishedqueue;public Jam Mer (Toastqueue butteredqueue, Toastqueue finishedqueue) {this.butteredqueue = Butteredqueue;this.finishedqueue = fiNishedqueue;} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {//blocks until next piece of toast is available block until next loaf toast T = Butteredqueue.take (); T.jam (); System.out.println (t); Finishedqueue.put (t);}} catch (Interruptedexception e) {System.out.println ("Coated Jam Interrupted");} SYSTEM.OUT.PRINTLN ("Spread jam Off");}} Using toast consume the Toastclass Eater implements Runnable {private Toastqueue finishedqueue;private int counter = 0;PU Blic Eater (Toastqueue finished) {finishedqueue = finished;} @Overridepublic void Run () {try {while (! Thread.interrupted ()) {Toast T = Finishedqueue.take ();//Verify that the toast was coming in order confirm that the bread has come//and that all pi Eces is getting jammed, all fragments getting squeezed if (t.getid ()! = counter++| | T.getstatus ()! = Toast.Status.JAMMED) {System.out.println (" ===>>>>error "+ t); System.exit (1);} else {System.out.println ("Eat!" + t);}}} catch (Interruptedexception e) {System.out.println ("Eater interrupted"); System.out.println ("Eater Off");}} /** * Main * * @author Lenovo * */public class Toastomatic {public static void main (string[] args) throws Interruptedexception {Toastqueue Dryq Ueue = new Toastqueue (); Toastqueue butteredqueue = new Toastqueue (); Toastqueue finishedqueue = new Toastqueue (); Executorservice exec = Executors.newcachedthreadpool (); Exec.execute (new Toaster (Dryqueue));//Toast Exec.execute (new Butterer (Dryqueue, Butteredqueue));//Butter Exec.execute (New jammer (Butteredqueue, Finishedqueue));//Upper Jam Exec.execute ( New Eater (Finishedqueue));//Eat TimeUnit.SECONDS.sleep (5); Exec.shutdownnow ();}} /**output:toast 0:drytoast 0:butteredtoast 0:jammed eat! Toast 0:jammedtoast 1:drytoast 1:butteredtoast 1:jammed eat! Toast 1:jammedtoast 2:drytoast 2:butteredtoast 2:jammed eat! Toast 2:jammed ... Toast 10:drytoast 10:butteredtoast 10:jammed eat! Toast 10:jammedtoast 11:drytoast 11:butteredtoast 11:jammed eat! Toast 11:jammedtoast 12:drytoast 12:butteredtoast 12:jammed eat! Toast 12:jammedtoast 13:drytoast 13:butteredtoast 13:jammed eat! Toast 13:jammedtoast 14:drytoast 14:butteredtoaSt 14:jammed Eat! Toast 14:jammed Interruptedtoaster interrupted eater off spreads jam interrupted spreads jam off butter interrupted butter offtoaster off */

Package Org.rui.thread.block2;import Java.io.ioexception;import Java.io.pipedreader;import java.io.PipedWriter; Import Java.util.random;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.timeunit;/** * tasks using pipelines for input, output * * @author Lenovo * */class Sender implements Runnable {private Rand Om rand = new Random (rivate);p 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 sleep 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) {//blocks until CharaCters is ThereSystem.out.println ("Read:" + (char) in.read () + ",");}} catch (IOException e) {System.out.println (e+ "receiver read execption");}}} public class Pipedio {//receiver receiverpublic static void main (string[] args) throws IOException, interruptedexception {Send ER sender = new sender (); Receiver receiver = new Receiver (sender); Executorservice Exec=executors.newcachedthreadpool (); Exec.execute (sender); Exec.execute (receiver); TimeUnit.SECONDS.sleep (4); Exec.shutdownnow ();}} /**outpt:read:a,read:b,read:c,read:d,read:e,read:f,read:g,read:h,read:i,read:j,read:k,read:l,read:m,read:n, Read:o,read:p,java.lang.interruptedexception:sleep interrupted sender sleep interruptedread:q,java.io.ioexception: Write End Deadreceiver Read Execption */



Java thread Producer-consumers and queues, tasks using pipelines for input, output explanation example--thinking java4

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.