One thread adds an operation, one thread does a subtraction, and multiple threads alternately run--synchronized

Source: Internet
Author: User

using synchronized

 PackageCom.pb.thread.demo5;/**using synchronized * One thread plus one operation, one thread doing subtraction, multiple threads running alternately *@authorDenny **/ Public classCount {Private intnum = 0; Private BooleanFlag =false;//Identification//addition     Public synchronized voidAdd () { while(flag) {Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); }        }         This. num++;//PlusSystem.out.println (Thread.CurrentThread (). GetName () + "..." + This. Num);  This. flag=true;//set Identity to TrueNotifyall ();//wake all threads that are frozen in the thread pool and wake them all up            }    //Subtraction     Public synchronized voidSub () { while(!flag) {            Try{wait (); } Catch(interruptedexception e) {e.printstacktrace (); }        }         This. num--;//minusSystem.out.println (Thread.CurrentThread (). GetName () + "..." + This. Num);  This. flag=false;//set Identity to TrueNotifyall ();//wake all threads that are frozen in the thread pool and wake them all up    }}

 PackageCom.pb.thread.demo5; Public classAddImplementsRunnable {Privatecount Count;  PublicAdd (count count) { This. count=count; } @Override Public voidrun () { while(true) {count.add (); }    }}//================ PackageCom.pb.thread.demo5; Public classSubImplementsRunnable {Privatecount Count;  PublicSub (count count) { This. count=count; } @Override Public voidrun () { while(true) {count.sub (); }    }} 

Test class

 PackageCom.pb.thread.demo5; Public classCounttest { Public Static voidMain (string[] args) {Count C=NewCount (); Add Add=NewAdd (c); Sub Sub=NewSub (c); Thread T1=NewThread (add); Thread T2=NewThread (add); Thread T3=NewThread (sub); Thread T4=NewThread (sub);        T1.start ();        T2.start ();        T3.start ();    T4.start (); }}

Results:

Thread-2 ..... 0thread-1 ..... 1thread-3 ..... 0thread-0 ..... 1thread-2 ..... 0thread-1 ..... 1thread-3 ..... 0thread-0 ..... 1thread-2 ..... 0
do not use synchronized
 PackageCom.pb.thread.demo4;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;/*** One thread plus one operation, one thread doing subtraction, multiple threads running alternately *@authorDenny **/ Public classCount {Private intnum = 0; Private Booleanflag=false;//IdentificationLock lock =NewReentrantlock ();//LockCondition add = Lock.newcondition ();//addition LockCondition sub = lock.newcondition ();//Subtraction Lock     Public voidAdd () {lock.lock ();//Lock        Try {             while(flag) {//Cycle Judgmentadd.await (); }             This. num++; System.out.println (Thread.CurrentThread (). GetName ()+ "........" + This. Num);  This. Flag =true;//Set IdentitySub.signal ();//Wake the specified thread}Catch(interruptedexception e) {e.printstacktrace (); }finally{lock.unlock (); }            }     Public voidSub () {Lock.lock ();//Lock        Try {             while(!flag) {//Cycle Judgmentsub.await (); }             This. num--; System.out.println (Thread.CurrentThread (). GetName ()+ "........" + This. Num);  This. Flag =false;//Set IdentityAdd.signal ();//Wake the specified thread}Catch(interruptedexception e) {e.printstacktrace (); }finally{lock.unlock (); }            }}

 Package Com.pb.thread.demo4;  Public class Implements Runnable {    private  count count;      Public Add (count count) {        this.count=Count;    }     @Override    publicvoid  run () {        while (true  ) {            count.add ();     }}}

 Package Com.pb.thread.demo4;  Public class Implements Runnable {    private  count count;      Public Sub (count count) {        this.count=Count;    }     @Override    publicvoid  run () {        while (true  ) {            count.sub ();     }}}

 PackageCom.pb.thread.demo4; Public classCounttest { Public Static voidMain (string[] args) {Count C=NewCount (); Add Add=NewAdd (c); Sub Sub=NewSub (c); Thread T1=NewThread (add); Thread T2=NewThread (add); Thread T3=NewThread (sub); Thread T4=NewThread (sub);        T1.start ();        T2.start ();        T3.start ();    T4.start (); }}
Results:
Thread-1 ..... 1thread-3 ..... 0thread-0 ..... 1thread-2 ..... 0thread-1 ..... 1thread-3 ..... 0thread-0 ..... 1thread-2 ..... 0

One thread adds one operation, one thread does minus one operation, and multiple threads alternately run--synchronized

Related Article

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.