For example, there are three threads. After 1 is executed, specify 2 for execution, 3 for execution after 2 for execution, and 1 for execution after 3 for execution.
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 ){
// TODO 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 ();
}
}
Www.2cto.com
Public void sub3 (int I ){
Lock. lock ();
Try {
While (shouldSub! = 3 ){
Try {
Condition3.await ();
} Catch (Exception e ){
// TODO 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 ){
// TODO 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 ();
}
}
}
}
Author: wwww1988600