Java线程中join()方法如何实现线程同步等待?

更新于
2026-10-04 10:26:29
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计209个文字,预计阅读时间需要1分钟。

使用join方法阻塞当前线程,等待特定线程执行完毕。以下是修改后的代码:

javapackage cn.mym.thread;

public class TestJoin { public static void main(String[] args) { Thread thread=new Thread(() -> { for (int i=0; i <10; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread running: + i); } });

thread.start(); try { thread.join(); // 等待thread线程执行完毕 } catch (InterruptedException e) { e.printStackTrace(); } }}

通过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

本文共计209个文字,预计阅读时间需要1分钟。

使用join方法阻塞当前线程,等待特定线程执行完毕。以下是修改后的代码:

javapackage cn.mym.thread;

public class TestJoin { public static void main(String[] args) { Thread thread=new Thread(() -> { for (int i=0; i <10; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread running: + i); } });

thread.start(); try { thread.join(); // 等待thread线程执行完毕 } catch (InterruptedException e) { e.printStackTrace(); } }}

通过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