Java thread series --- condition example

Source: Internet
Author: User

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

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.