Java thread series-thread synchronization and mutex

Source: Internet
Author: User

For example, if the Sub-thread runs for 10 times and the main thread runs for 100 times, how to design

Public class threadcommunication {

Public static void main (string [] ARGs ){


Final output = new output ();

// Subthread
New thread (
New runnable (){
Public void run (){
For (INT I = 1; I <= 50; I ++ ){
Output. sub (I );
}
}
}). Start ();
// Main thread
For (INT I = 1; I <= 50; I ++ ){
Output. Main (I );
}
}

}
Class output {
Private Boolean flag = true; // thread status
Public synchronized void sub (int I ){
While (! Flag ){
Try {
This. Wait ();
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
For (Int J = 1; j <= 10; j ++ ){
System. Out. println ("+ J in the subthread" + I + "times );
}
Flag = false;
This. Y (); // wake up the thread
}

Public synchronized void main (int I ){
While (FLAG ){
Try {
This. Wait ();
} Catch (interruptedexception e ){
E. printstacktrace ();
}
}
For (Int J = 1; j <= 100; j ++ ){
System. Out. println ("main thread number" + I + "times in" + J );
}
Flag = true;
This. Policy ();
}

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.