Java线程的join()方法如何实现子线程等待父线程执行完毕再继续?
- 内容介绍
- 文章标签
- 相关推荐
本文共计177个文字,预计阅读时间需要1分钟。
通过join方法阻塞当前线程,等待其他线程执行完毕。+package+cn.mym.thread;+public+class+TestJoin+{+public+static+void+main(String[]+args)+{+Thread+thread+=+new+Thread5();+thread.start();+int+i+=+0;+while(i<10){+try{+Thread.sleep(500);+}+catch(InterruptedException+e){+e.printStackTrace();+}+i++;+}+}+}
通过join方法阻塞其它线程,等待该线程执行完毕。package cn.mym.thread; public class TestJoin { public static void main(String[] args) { Thread5 thread = new Thread5(); thread.start(); int i = 0; while(i<10){ try { Thread.sleep(50); if(i == 5){ thread.join(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("world"); i++; } } } class Thread5 extends Thread{ @Override public void run() { int i = 0; while(i<10){ try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread4"); i++; } } } //====================执行结果================= world Thread4 Thread4 world Thread4 world Thread4 world Thread4 world Thread4 Thread4 Thread4 Thread4 Thread4 world world world world world
本文共计177个文字,预计阅读时间需要1分钟。
通过join方法阻塞当前线程,等待其他线程执行完毕。+package+cn.mym.thread;+public+class+TestJoin+{+public+static+void+main(String[]+args)+{+Thread+thread+=+new+Thread5();+thread.start();+int+i+=+0;+while(i<10){+try{+Thread.sleep(500);+}+catch(InterruptedException+e){+e.printStackTrace();+}+i++;+}+}+}
通过join方法阻塞其它线程,等待该线程执行完毕。package cn.mym.thread; public class TestJoin { public static void main(String[] args) { Thread5 thread = new Thread5(); thread.start(); int i = 0; while(i<10){ try { Thread.sleep(50); if(i == 5){ thread.join(); } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("world"); i++; } } } class Thread5 extends Thread{ @Override public void run() { int i = 0; while(i<10){ try { Thread.sleep(50); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Thread4"); i++; } } } //====================执行结果================= world Thread4 Thread4 world Thread4 world Thread4 world Thread4 world Thread4 Thread4 Thread4 Thread4 Thread4 world world world world world

