(接上文《JVM调试常用命令——jstack命令与Java线程栈(2)》)
2.1.3.2、当前线程调用目前线程的join方法,等待后者执行完成
join方法可以让一个线程持续等待到另一个线程完成运行后,再继续进行运行。下面我们就来看一下使用join方法让一个线程进入WATING状态时,在jstack命令结果中的打印效果。
// ......之前的代码片段省略
public static void main(String[] args) {
Thread thread1 = new Thread(new MyThread1(), "thread1");
Thread thread2 = new Thread(new MyThread2(thread1), "thread2");
thread1.start();
thread2.start();
}
private static class MyThread2 implements Runnable {
private Thread joinThread;
public MyThread2(Thread joinThread) {
this.joinThread = joinThread;
}
@Override
public void run() {
Thread currentThread = Thread.currentThread();
System.out.println("当前线程[" + currentThread.getName() + "]使用join进入等待");
try {
this.joinThread.join();
} catch (InterruptedException e) {
e.printStackTrace(System.out);
}
System.out.println("当前线程[" + currentThread.getName()