Title: Now two threads, you can operate the same variable, implement a thread on the variable plus 1, a thread on the variable minus 1, the realization of alternating, to 10 rounds, the variable initial value is zero.
Import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;class sharedata {private int number = 0; Lock lock = new Reentrantlock (); Condition Condition = Lock.newcondition (); public void increment () throws Exception {Lock.lock (); try {while (number! = 0) {condition.await ();//this.wait (); } ++number; System.out.println (Thread.CurrentThread (). GetName () + "\ T" + number); Condition.signalall ();//this.notifyall (); } catch (Exception e) {e.printstacktrace (); } finally {Lock.unlock (); }} public void Decrement () throws Exception {Lock.lock (); try {while (number = = 0) {condition.await ();//this.wait (); }--number; System.out.println (Thread.CurrentThread (). GetName () + "\ T" + number); ConditIon.signalall ();//this.notifyall (); } catch (Exception e) {e.printstacktrace (); } finally {Lock.unlock (); }}//======== This is the most primitive notation used synchronized========/*public synchronized void increment () throws Exception{while (number!). = 0) {this.wait ();} ++number; System.out.println (Thread.CurrentThread (). GetName () + "\ T" +number); This.notifyall ();} Public synchronized void Decrement () throws exception{while (number = = 0) {this.wait ();} --number; System.out.println (Thread.CurrentThread (). GetName () + "\ T" +number); This.notifyall ();} */}/** * Title: Now two threads, you can manipulate the same variable, implement a thread to the variable plus 1, a thread to the variable minus 1, * realize alternating, to 10 rounds, the variable initial value is zero. * * @author admin * Create four thread operations resources (cohesion, low coupling) */public class ThreadDemo2 {public static void main (string[] args) {fi nal sharedata sd = new Sharedata (); New Thread (New Runnable () {@Override public void run () {for (int i = 1; I <= 10; i++) {try {thread.sleep (200); Sd.increment (); } catch (Exception e) {e.printstacktrace (); }}}, "AA"). Start (); New Thread (New Runnable () {@Override public void run () {for (int i = 1; I <= 10; i++) {try {thread.sleep (300); Sd.decrement (); } catch (Exception e) {e.printstacktrace (); }}}, "BB"). Start (); New Thread (New Runnable () {@Override public void run () {for (int i = 1; I <= 10; i++) {try {Thread.Sleep (400); Sd.increment (); } catch (Exception e) {e.printstacktrace (); }}}, "CC"). Start (); New Thread (New Runnable () {@Override public void run () {for (int i = 1; I <= 10; i++) {try {thread.sleep (500); Sd.decrement (); } catch (Exception e) {e.printstacktrace (); }}}, "DD"). Start (); }}
In this need to pay attention to a problem in the method of the shared object to replace if to while, solve the problem of false wake.
Alternative multithreaded producer and consumer model