One thread adds one operation, and one thread reduces one operation. multiple threads run alternately at the same time -- synchronized, thread -- synchronized

Source: Internet
Author: User

One thread adds one operation, and one thread reduces one operation. multiple threads run alternately at the same time -- synchronized, thread -- synchronized
Use synchronized

 

 

Package com. pb. thread. demo5;/** use synchronized * to add one operation to a thread and perform subtraction on a thread, multiple threads run alternately ** @ author Denny **/public class Count {private int num = 0; private boolean flag = false; // identifier // add public synchronized void add () {while (flag) {try {wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} this. num ++; // Add System. out. println (Thread. currentThread (). getName () + "........ "+ this. num); th Is. flag = true; // set it to true notifyAll (); // wake up all threads frozen in the thread pool and wake up all threads} // subtract public synchronized void sub () {while (! Flag) {try {wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} this. num --; // minus System. out. println (Thread. currentThread (). getName () + "........ "+ this. num); this. flag = false; // set the flag to true notifyAll (); // wake up all threads frozen in the thread pool and wake up all threads }}

 

 

 

 

package com.pb.thread.demo5;public class Add implements Runnable {    private Count count;    public Add(Count count){        this.count=count;    }     @Override    public void run() {        while(true){            count.add();        }    }}//================package com.pb.thread.demo5;public class Sub implements Runnable {    private Count count;    public Sub(Count count){        this.count=count;    }     @Override    public void run() {        while(true){            count.sub();        }    }} 

 

Test class

 

package com.pb.thread.demo5;public class CountTest {    public static void main(String[] args) {        Count c=new Count();        Add add=new Add(c);        Sub sub=new Sub(c);        Thread t1=new Thread(add);        Thread t2=new Thread(add);        Thread t3=new Thread(sub);        Thread t4=new Thread(sub);        t1.start();        t2.start();        t3.start();        t4.start();    }}

 

Result:

 
Thread-2........0Thread-1........1Thread-3........0Thread-0........1Thread-2........0Thread-1........1Thread-3........0Thread-0........1Thread-2........0
  Do not use synchronized
Package com. pb. thread. demo4; import java. util. concurrent. locks. condition; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock;/*** one thread adds one operation, one thread performs subtraction, and multiple threads run alternately * @ author Denny **/public class Count {private int num = 0; private boolean flag = false; // identify Lock lock = new ReentrantLock (); // lock Condition add = Lock. newCondition (); // addition lock Condition sub = lock. newCond Ition (); // subtraction lock public void add () {lock. lock (); // lock try {while (flag) {// cyclically judge add. await ();} this. num ++; System. out. println (Thread. currentThread (). getName () + "........ "+ this. num); this. flag = true; // set the ID sub. signal (); // wake up the specified Thread} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock () ;}} public void sub () {lock. lock (); // lock try {while (! Flag) {// judge sub cyclically. await ();} this. num --; System. out. println (Thread. currentThread (). getName () + "........ "+ this. num); this. flag = false; // set the ID to add. signal (); // wake up the specified Thread} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock ();}}}
 

 

 

package com.pb.thread.demo4;public class Add implements Runnable {    private Count count;    public Add(Count count){        this.count=count;    }     @Override    public void run() {        while(true){            count.add();        }    }}

 

 

package com.pb.thread.demo4;public class Sub implements Runnable {    private Count count;    public Sub(Count count){        this.count=count;    }     @Override    public void run() {        while(true){            count.sub();        }    }}

 

 

package com.pb.thread.demo4;public class CountTest {    public static void main(String[] args) {        Count c=new Count();        Add add=new Add(c);                Sub sub=new Sub(c);        Thread t1=new Thread(add);        Thread t2=new Thread(add);        Thread t3=new Thread(sub);        Thread t4=new Thread(sub);        t1.start();        t2.start();        t3.start();        t4.start();    }}
  Result: 
Thread-1........1Thread-3........0Thread-0........1Thread-2........0Thread-1........1Thread-3........0Thread-0........1Thread-2........0
 

 

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.