Thread.join详解
阅读原文时间:2023年07月08日阅读:2

/**
* 如果某个线程在另一个线程t上调用t.join;那么此线程将被挂起,直到目标t线程的结束才恢复即t.isAlive返回为假
*
* @date:2018年6月27日
* @author:zhangfs
*
*
*/
public class ClientDemo {

public static void main(String\[\] args) {  
    SleepThread sleepThread1 = new SleepThread("sleepThread1", 1500),  
            sleepThread2 = new SleepThread("sleepThread2", 1500);

    JoinThread joinThread1 = new JoinThread("joinThread1", sleepThread1),  
            joinThread2 = new JoinThread("joinThread2", sleepThread2);

    sleepThread2.interrupt();

}  

}

p.p1 { margin: 0; font: 11px Monaco }
p.p2 { margin: 0; font: 11px Monaco; color: rgba(147, 26, 104, 1) }
p.p3 { margin: 0; font: 11px Monaco; min-height: 15px }
p.p4 { margin: 0; font: 11px Monaco; color: rgba(126, 80, 79, 1) }
p.p5 { margin: 0; font: 11px Monaco; color: rgba(119, 119, 119, 1) }
p.p6 { margin: 0; font: 11px Monaco; color: rgba(78, 144, 114, 1) }
span.s1 { color: rgba(147, 26, 104, 1) }
span.s2 { color: rgba(0, 0, 0, 1) }
span.s3 { color: rgba(3, 38, 204, 1) }
span.s4 { color: rgba(126, 80, 79, 1) }
span.s5 { color: rgba(145, 175, 203, 1) }
span.s6 { color: rgba(57, 51, 255, 1) }
span.Apple-tab-span { white-space: pre }

public class SleepThread extends Thread {

private int duration;

public SleepThread(String name, int sleepTime) {

super(name);

this.duration = sleepTime;

start();

}

@Override

public void run() {

// TODO Auto-generated method stub

// super.run();

try {

sleep(duration);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

// e.printStackTrace();

System.out.println(getName() + " was interrupted. is interrupted is :" + isInterrupted());

return;

}

System.out.println(getName() + " has awakened");

}

}

p.p1 { margin: 0; font: 11px Monaco }
p.p2 { margin: 0; font: 11px Monaco; min-height: 15px }
p.p3 { margin: 0; font: 11px Monaco; color: rgba(3, 38, 204, 1) }
p.p4 { margin: 0; font: 11px Monaco; color: rgba(119, 119, 119, 1) }
p.p5 { margin: 0; font: 11px Monaco; color: rgba(78, 144, 114, 1) }
span.s1 { color: rgba(147, 26, 104, 1) }
span.s2 { color: rgba(3, 38, 204, 1) }
span.s3 { color: rgba(126, 80, 79, 1) }
span.s4 { color: rgba(0, 0, 0, 1) }
span.s5 { color: rgba(145, 175, 203, 1) }
span.s6 { color: rgba(57, 51, 255, 1) }
span.Apple-tab-span { white-space: pre }

public class JoinThread extends Thread {

private SleepThread sleepThread;

public JoinThread(String name, SleepThread sleepThread) {

super(name);

this.sleepThread = sleepThread;

start();

}

@Override

public void run() {

// TODO Auto-generated method stub

try {

sleepThread.join();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

// e.printStackTrace();

System.out.println("interrupted ");

}

System.out.println(getName() + "  Join Complete");

}

}

output:

p.p1 { margin: 0; font: 11px Monaco }

sleepThread2 was interrupted. is interrupted is :false

joinThread2  Join Complete

sleepThread1 has awakened

joinThread1  Join Complete