Java Learning Notes (42)-Producer consumer models

Source: Internet
Author: User

Wait (), notify ()
/* * Wait (), notify () * 1. Two methods can only be executed in the synchronized code block, because the thread that holds the lock will only have the lock * 2 in sync. Two methods when you manipulate a thread in synchronization, you must identify the object lock held by the operating thread * 3. Wait and wake must be the same object lock */ Public  class Test05 {     Public Static voidMain (string[] args) {MyThread3 mt=NewMyThread3 (); Thread th=NewThread (MT,"Thread One"); Th.start ();Try{Thread.Sleep ( -);//The main thread sleeps for 2 seconds, allowing thread th to wait in the pool for a while}Catch(Interruptedexception e)        {E.printstacktrace (); }//Interrupts thread in the wait pool in Mt object th        //th.interrupt ();Synchronized (MT) {mt.notify ();//wake-up object A thread in the wait pool of Mt}    }} class MyThread3 implements Runnable{@Override Public voidRun () {//Synchronous code blockSynchronized ( This) {System.out.println ("* * * Enter Synchronous code block");Try{Wait ();//thread enters the wait pool, is in a blocked stateSystem.out.println ("***wait the lock again."); }Catch(Interruptedexception e) {System.out.println ("***"+thread.currentthread (). GetName () +"Be interrupted!" "); } for(intI=1; i<= -; i++) {System.out.println (Thread.CurrentThread (). GetName () +"***"+i); } System.out.println ("* * * Synchronization code block execution ends! "); }    }}
Producer, consumer model
/* Thread communication: Multiple threads operate on the same resource, but the action is different * producer, consumer model * WAIT () and notify () methods are generally used in producer and consumer models to wait for synchronized data */ Public  class Test06 {     Public Static voidMain (string[] args) {Person person =NewPerson (); Input in =NewInput (person); Output out =NewOutput (person); Thread Th1 =NewThread (In,"producers have produced:");//Producing personThread Th2 =NewThread (out,"Consumers are consuming:");//Remove personTh1.start ();    Th2.start (); }} class  person {String name; String sex;BooleanFlag =true;//True indicates that a person needs to be generated, false means that the person removed}//production, into class Input implements Runnable {    Privateperson person; PublicInput (person person) { This. person = person; } @Override Public voidRun () {intx =0; while(true) {synchronized (person) {if(Person.flag) {if(x = =0) {//judgment interval to produce different peoplePerson.name ="Tom"; Person.sex ="Male"; }Else{Person.name ="Zhang San"; Person.sex ="female"; } x = (x +1) %2;//interval to produce different peoplePerson.flag =false;//Put it once, take it oncePerson.notify ();//wake-up thread of a person}Else{Try{person.wait ();//If you do not need to produce a person, wait}Catch(Interruptedexception e)                    {E.printstacktrace (); }                }            }        }    }}//consumption, out class Output implements Runnable {    Privateperson person; PublicOutput (person person) { This. person = person; } @Override Public voidRun () { while(true) {synchronized (person) {if(!person.flag) {System.out.println (Thread.CurrentThread (). GetName () +person.name +"***"+ Person.sex); Person.flag =true; Person.notify ();//wake-up thread for production people}Else{Try{person.wait ();//If you do not need to remove the person, wait}Catch(Interruptedexception e)                    {E.printstacktrace (); }                }            }        }    }}

Java Learning Notes (42)-Producer consumer models

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.