Brief Introduction:
Using the join and interrupt functions in Java multithreading
"Java Programming thought" P669 ~ P670
A thread can invoke the join () method on another thread, and the effect is to wait for a period of time until the second thread ends before execution continues.
If a thread is raised with T.join () on another thread T, the thread is suspended until the target thread T is finished (that is, t.isalive () is returned as false)
Calls to the join () method can be interrupted by invoking the interrupt () method on the calling thread, which requires the use of the Try-catch
Sleeper.java
Package com.anialy.test.multithread.JoinAndInterrupt;
public class Sleeper extends Thread {
private int duration;
Public Sleeper (String name, int sleeptime) {
setname (name);
This.duration = Sleeptime;
Start (); Starting in the constructor
@Override public
void Run () {try{sleep
(duration);
} catch ( Interruptedexception e) {
System.out.println (String.Format ("%s was interrupted. Isinterrupted ():%b "
, GetName (), isinterrupted ()));
return;
}
System.out.println (GetName () + "has awakened");
}
Joiner.java
Package com.anialy.test.multithread.JoinAndInterrupt;
public class Joiner extends Thread {
private sleeper sleeper;
Public Joiner (String name, sleeper sleeper) {
setname (name);
This.sleeper = sleeper;
Start ();
}
@Override public
Void Run () {
try {
//If a thread is raised with T.join () on another thread T, this thread will be suspended,
// Recovery (that is, t.isalive () returned as false)
Sleeper.join (),
catch (Interruptedexception e) {
System.out.println ("interrupted.");
}
System.out.println (GetName () + "join completed");
}
Test1.java
Package com.anialy.test.multithread.JoinAndInterrupt;
public class Test1 {public
static void Main (string[] args) {
sleeper sleeper1 = new Sleeper ("Thread A-1500", 1500); C23/>joiner joiner1 = new Joiner ("Thread Join-a", sleeper1);
}
Output:
You can see that the JOIN-A thread does not complete until the first thread sleeps for 1500 milliseconds
Test.java
Package com.anialy.test.multithread.JoinAndInterrupt;
public class Test2 {public
static void Main (string[] args) {
sleeper sleeper = new Sleeper ("Thread A-1500", 1500);
joiner Joiner = new Joiner ("Thread Join-a", sleeper);
Sleeper.interrupt ();
}
Output:
Join () was interrupted because the sleeper thread was used with Interrupt,sleeper before it was completed.