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 = 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 = 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 ();
}
}
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 ();
}
}
}
}