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"