共计 851 个字符,预计需要花费 3 分钟才能阅读完成。
定义
等待该线程终止,比如 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 才执行完。
正文完
发表至: java
2019-07-08