定义
等待该线程终止,比如A线程调用了B线程的join,那么A线程要等到B线程执行完后,才可以继续执行。
示例
public class JoinDemo {
static class JoinThread1 implements Runnable {
Thread thread;
public JoinThread1(Thread thread) {
this.thread = thread;
}
@Override
public void run() {
System.out.println("thread1 start");
try {
thread.join();
System.out.println("thread1 end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class JoinThread2 implements Runnable {
@Override
public void run() {
System.out.println("thread2 start");
try {
Thread.sleep(10000);
System.out.println("thread2 end");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JoinThread2 joinThread2 = new JoinThread2();
Thread thread2 = new Thread(joinThread2);
JoinThread1 joinThread1 = new JoinThread1(thread2);
Thread thread1 = new Thread(joinThread1);
thread1.start();
thread2.start();
}
}
运行结果如下:
线程1执行的时候,调用线程2的join,线程1不休眠,线程2休眠了10秒,从结果看出来,线程2执行完后,线程1才执行完。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。