Interview question: the sub-thread loops 10 times, the main thread loops 100 times, and then returns to the sub-thread loop 10 times, and then returns to the main thread loop 100 times, so the loop is 50 times, write the program

Source: Internet
Author: User

Public class threadtest {
Public static void main (string [] ARGs) throws interruptedexception {
// Todo auto-generated method stub
New threadtest (). INIT ();
}
Public void Init () throws interruptedexception
{
Final business = new business ();
New thread (New runnable ()
{
Public void run (){
For (INT I = 0; I <50; I ++)
{
Business. subthread (I );
}
}
}
). Start ();
Thread. Sleep (1000); // This row is executed first by the subthread to let the main thread out of the CPU
For (INT I = 0; I <50; I ++)
{
Business. mainthread (I );
}
}
Class business
{
// Boolean bshouldsub = true;
Public synchronized void mainthread (int I) throws interruptedexception
{
For (Int J = 0; j <100; j ++)
{
System. Out. println (thread. currentthread (). getname () + ": yu_ I =" + I + ", j =" + J );
}
This. Policy ();
Try {
This. Wait ();
} Catch (interruptedexception e ){
E. printstacktrace ();
}

}
Public synchronized void subthread (int I)
{
For (Int J = 0; j <10; j ++)
{
System. Out. println (thread. currentthread (). getname () + ": bing_ I =" + I + ", j =" + J );
}
This. Policy ();
Try {
This. Wait ();
} Catch (interruptedexception e ){
E. printstacktrace ();
}

}
}
}
 

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.