Wake up specified line layer object in Java new version

Source: Internet
Author: User

Importjava.util.concurrent.locks.*; classDo9 { Public Static voidMain (string[] args) {Resource R=NewResource (); Shengchan SC=NewShengchan (R); Xiaoshou XS=NewXiaoshou (R); Thread Th1=NewThread (SC); Thread Th2=NewThread (SC); Thread Th3=NewThread (XS); Thread Th4=NewThread (XS);        Th1.start ();        Th2.start ();        Th3.start ();    Th4.start (); }}classresource{PrivateString name; Private intCount=1; Private Booleanflag=false; //Create a lock pair likeLock lock=NewReentrantlock (); //Gets the monitor object for the lock by the existing locksCondition shengchan_con=lock.newcondition ();//Create a Producer objectCondition xiaofei_con=lock.newcondition ();//Create consumer Objects     Public  voidset (String name) {Lock.lock (); Try        {             while(flag)Try{shengchan_con.await ();}Catch(Interruptedexception e) {} This. name=name+count; Count++; System.out.println (Thread.CurrentThread (). GetName ()+".. Producer: " + This. Name); Flag=true;        Xiaofei_con.signal (); }        finally{lock.unlock (); }                        }     Public synchronized voidout () {lock.lock (); Try        {             while(!flag)Try{xiaofei_con.await ();}Catch(Interruptedexception e) {} System.out.println (Thread.CurrentThread (). GetName ()+".. Consumer ... "+ This. Name); Flag=false;        Shengchan_con.signal (); }        finally{lock.unlock (); }            }}classShengchanImplementsrunnable{PrivateResource R; Shengchan (Resource r) { This. r=R; }     Public voidrun () { while(true)        {          Try{Thread.Sleep (150);}Catch(Interruptedexception e) {} r.set (Duck); }    }}classXiaoshouImplementsrunnable{PrivateResource R; Xiaoshou (Resource r) { This. r=R; }     Public voidrun () { while(true)        {        Try{Thread.Sleep (150);}Catch(Interruptedexception e) {} r.out (); }    }}

Wake up specified line layer object in Java new version

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.