join()
代码:
package concurrent._join; public class Demo { public static void main(String[] args) throws InterruptedException { ThreadA threadA = new ThreadA(); ThreadB threadB = new ThreadB(threadA); String threadName = Thread.currentThread().getName(); System.out.println(threadName + "已经启动了"); threadB.run(); // threadA.join(); // System.out.println(threadName + "等待子线程的join方法结束了"); threadB.join(); System.out.println(threadName + "等待子线程的join方法结束了"); } } class ThreadA extends Thread{ public ThreadA(){ super("ThreadA"); } @Override public void run() { String threadName = this.getName(); System.out.println(threadName + "已经启动了"); for(int i = 0 ; i < 5 ; i++){ System.out.println(threadName + "开始第" + i + "次的睡眠"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(threadName + "已经结束了"); } } class ThreadB extends Thread{ Thread thread; public ThreadB(Thread thread){ super("ThreadB"); this.thread = thread; } @Override public void run() { String threadName = this.getName(); System.out.println(threadName + "已经启动了"); try { thread.start(); thread.join(); System.out.println(threadName + "等待子线程的join方法结束了"); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadName + "已经结束了"); } }
结果:
main已经启动了
ThreadB已经启动了
ThreadA已经启动了
ThreadA开始第0次的睡眠
ThreadA开始第1次的睡眠
ThreadA开始第2次的睡眠
ThreadA开始第3次的睡眠
ThreadA开始第4次的睡眠
ThreadA已经结束了
ThreadB等待子线程的join方法结束了
ThreadB已经结束了
main等待子线程的join方法结束了
修改代码:
package concurrent._join; public class Demo { public static void main(String[] args) throws InterruptedException { ThreadA threadA = new ThreadA(); ThreadB threadB = new ThreadB(threadA); String threadName = Thread.currentThread().getName(); System.out.println(threadName + "已经启动了"); threadA.start(); threadB.start(); // threadA.join(); // System.out.println(threadName + "等待子线程的join方法结束了"); threadB.join(); System.out.println(threadName + "等待子线程的join方法结束了"); } } class ThreadA extends Thread{ public ThreadA(){ super("ThreadA"); } @Override public void run() { String threadName = this.getName(); System.out.println(threadName + "已经启动了"); for(int i = 0 ; i < 5 ; i++){ System.out.println(threadName + "开始第" + i + "次的睡眠"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(threadName + "已经结束了"); } } class ThreadB extends Thread{ Thread thread; public ThreadB(Thread thread){ super("ThreadB"); this.thread = thread; } @Override public void run() { String threadName = this.getName(); System.out.println(threadName + "已经启动了"); try { // thread.start(); thread.join(); System.out.println(threadName + "等待子线程的join方法结束了"); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(threadName + "已经结束了"); } }
结果:
main已经启动了
ThreadA已经启动了
ThreadA开始第0次的睡眠
ThreadB已经启动了
ThreadA开始第1次的睡眠
ThreadA开始第2次的睡眠
ThreadA开始第3次的睡眠
ThreadA开始第4次的睡眠
ThreadA已经结束了
ThreadB等待子线程的join方法结束了
ThreadB已经结束了
main等待子线程的join方法结束了