Use of join in java Multithreading

Source: Internet
Author: User

For the use of join in java multithreading, see the following two simple thread classes.
1. Sleep
Package com. demo;
Public class Sleeper extends Thread {
Private int duration;
Public Sleeper (int duration, String name ){
Super (name );
This. duration = duration;
Start ();
}
Public void run (){
 
Try {
Sleep (duration );
} Catch (InterruptedException e ){
System. out. println (getName () + "is interupted .");
Return;
}
System. out. println (getName () + "has wakened ");
 
}
 
/**
* @ Param args
*/
Public static void main (String [] args ){
Sleeper sleeper1 = new sleeperer (1500, "sleeper1 ");
Sleeper sleeper2 = new sleeperer (1500, "sleeper2 ");
Joiner joiner1 = new Joiner (sleeper1, "joiner1 ");
Joiner joiner2 = new Joiner (sleeper2, "joiner2 ");
Sleeper1.interrupt ();
}
}
 
2. Entrants
Class Joiner extends Thread {
Private Thread t;
Public Joiner (Thread t, String name ){
Super (name );
This. t = t;
Start ();
}
Public void run (){
Try {

T. join ();

} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
System. out. println (getName () + "is completed ");
}
}
Analysis of code running results:
Use case description of join: when there are two threads, A and B, when thread A calls A on thread B. during join (), thread B is suspended until thread A ends or thread A calls the interrupt () method.
 
 
========================================================== ============================
The following is the running result of this Code:
Sleeper1 is interupted.
Joiner1 is completed
Sleeper2has wakened
Joiner2 is completed

Author: "690360459-qq-com"
 

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.