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

更新于
2026-10-04 09:41:21
0阅读来源: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方法阻塞其它线程,等待该线程执行完毕。
阅读全文

本文共计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方法阻塞其它线程,等待该线程执行完毕。
阅读全文