Java thread join() method study notes

A thread can call the join() method on other threads. The effect is to wait for a period of time until the second thread ends before continuing. If a thread calls t.join() on another thread t, this thread will be suspended and will not resume until the target thread t ends (that is, t.isAlive() returns false).

You can also bring a timeout parameter when calling the join() method (units can be milliseconds, or milliseconds and nanoseconds), so if the target thread has not ended when this time expires, the join() method can always return .

The call to the join() method can be interrupted by calling the interrupted() method on the calling thread. At this time, a try-catch clause is required.

class Sleeper extends Thread{
    
    
	private int duration;
	public Sleeper(String name,int sleepTime) {
    
    
		super(name);
		duration=sleepTime;
		start();
	}
	public void run() {
    
    
		try {
    
    
			sleep(duration);
		}catch(InterruptedException e) {
    
    
			System.out.println(getName()+" was interrupted. "+" is interrupted: "+isInterrupted());
			return;
		}
		System.out.println(getName()+" has awakened");
	}
}
class Joiner extends Thread{
    
    
	private Sleeper sleeper;
	public Joiner(String name,Sleeper sleeper) {
    
    
		super(name);
		this.sleeper=sleeper;
		start();
	}
	public void run() {
    
    
		try {
    
    
			sleeper.join();
		}catch(InterruptedException e) {
    
    
			System.out.println("Interrupted");
		}
		System.out.println(getName()+" join completed");
	}
}
public class Joining {
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
        Sleeper sleepy=new Sleeper("Sleepy",1500),
        		grumpy=new Sleeper("grumpy",1500);
        Joiner dopey=new Joiner("Dopey",sleepy),
        		doc=new Joiner("Doc",grumpy);
        grumpy.interrupt();
	}

}
/*
grumpy was interrupted.  is interrupted: false
Doc join completed
Sleepy has awakened
Dopey join completed
*/

Guess you like

Origin blog.csdn.net/weixin_43916777/article/details/104228699