Thread.join使用场景

Thread.join使用场景:
如下例子,有一个任务需要花10秒才完成,现可分2个线程各做一半任务,
2个线程同时跑,5秒后即可完成任务并得到结果。
所以join可应用于,需要多线程执行任务以减少主线程花费时间的场景。
public class ThreadJoin {
    public static void main(String[] args) throws InterruptedException {
        final List list = new ArrayList();
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add("a");
                System.out.println("list add a");
            }
        });
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add("b");
                System.out.println("list add b");
            }
        });
        t1.start();
        t2.start();

        //main线程阻塞,直至t1线程执行完毕
        t1.join();
        //main线程阻塞,直至t2线程执行完毕
        t2.join();
        System.out.println("list.size : "  + list.size());
    }
}
输出:
list add a
list add b
list.size : 2
### Java 中 `Thread.join` 方法的使用 在多线程编程中,有时主线程需要等待其他子线程完成后再继续执行。此时可以使用 `join()` 方法来实现这一功能。当调用某个线程对象的 `join()` 方法时,当前线程会阻塞直到该线程结束[^1]。 #### 基本语法 ```java public final void join() throws InterruptedException; ``` 此方法会使当前正在运行的线程暂停并等待指定的线程终止。如果抛出了 `InterruptedException`,则表示另一个线程已中断了当前线程。 #### 使用示例 下面是一个简单的例子展示如何利用 `join()` 来确保两个并发工作的线程按顺序完成: ```java class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; } @Override public void run() { System.out.println(name + " is running"); try { // Simulate some work being done by sleeping. sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name + " has finished its task."); } } public class JoinExample { public static void main(String[] args) { MyThread t1 = new MyThread("Thread-2"); t1.start(); // Start first thread try { t1.join(); // Wait until t1 finishes before starting next line } catch (InterruptedException e) { e.printStackTrace(); } t2.start(); // Only starts after t1 completes try { t2.join(); // Wait again for second thread to finish } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Both threads have completed their tasks."); } } ``` 在这个程序里,通过两次调用了 `t1.join()` 和 `t2.join()` ,保证了只有在线程 T1 完成之后才会启动T2,并且整个应用程序会在所有的工作都完成后才打印最终的消息。 #### 解决线程同步问题的方法 除了上述提到的方式外,在处理更复杂的场景下还可以考虑采用更高层次抽象工具如 `CountDownLatch`, `CyclicBarrier` 或者是基于锁机制(`ReentrantLock`)来进行更加精细控制下的协调操作[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值