Package Cn.itcast.heima2;import Java.util.concurrent.atomic.atomicinteger;import Java.util.concurrent.locks.condition;import Java.util.concurrent.locks.lock;import Java.util.concurrent.locks.reentrantlock;public class Threeconditioncommunication {public static void main (string[] args) {final business business = new Business (), New Thread (new Runnable () {@Override public void run () {for (int i=1;i <=50;i++) {business.sub2 (i);}} }). Start (); New Thread (New Runnable () {@Override public void run () {for (int i=1;i<=50;i++) {business.sub3 (i)}}). Start (); for (int i=1;i<=50;i++) {business.main (i);}} Static class Business {lock lock = new Reentrantlock (); Condition condition1 = Lock.newcondition (); Condition condition2 = Lock.newcondition (); Condition Condition3 = Lock.newcondition (); private int shouldsub = 1; public void sub2 (int i) {lock.lock (), try{while (shouldsub! = 2) {try {condition2.await ()} catch (Exception e) {//TOD O auto-generated Catch block E.printstacKtrace (); }} for (int j=1;j<=10;j++) {System.out.println ("Sub2 thread sequence of" + j + ", loop of" + i);} Shouldsub = 3; Condition3.signal (); }finally{Lock.unlock ();}} public void sub3 (int i) {lock.lock (), try{while (shouldsub! = 3) {try {condition3.await ()} catch (Exception e) {//TOD O auto-generated Catch block E.printstacktrace (); }} for (int j=1;j<=20;j++) {System.out.println ("SUB3 thread sequence of" + j + ", loop of" + i);} Shouldsub = 1; Condition1.signal (); }finally{Lock.unlock ();}} public void Main (int i) {lock.lock (), try{while (shouldsub! = 1) {try {condition1.await ();} catch (Exception e) {//TOD O auto-generated Catch block E.printstacktrace (); }} for (int j=1;j<=100;j++) {System.out.println ("main thread sequence of" + j + ", loop of" + i);} Shouldsub = 2; Condition2.signal (); }finally{Lock.unlock ();}} }}
Three threads communicate with each other thread 1 start thread 2 2 start 3 3 start 1