java中Thread.join()方法

1. Thread.join()方法是什么
Thread.join()方法是Thread类中的一个方法,该方法的定义是等待该线程终止。其实就是join()方法将挂起调用线程的执行, 直到被调用的线程完成它的执行。
举例说明:在主线程中调用t1.join()方法,主线程将等待t1线程终止。join()方法挂起主线程的执行,直到t1执行完毕后主线程才接着执行。
2. Thread.join如何使用
现在有T1、T2两个线程,你怎样保证T2在T1执行完后执行?

public class ThreadJoin {

    public static void main(String[] args){
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    System.out.println("thread t1 is running");
                    Thread.sleep(5000);
                    System.out.println("thread t1 is over");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    //t1.join();
                    System.out.println("thread t2 is running");
                    Thread.sleep(5000);
                    System.out.println("thread t2 is over");
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        });
        t2.start();
    }
    }

运行结果如下:

thread t2 is running
thread t1 is running
thread t1 is over
thread t2 is over

可以看出t2并没有等待t1执行结束后才执行,两者是并发执行的。

使用Thread.join()方法,在线程t2中执行t1.join()方法,此时调用线程是t2,被调用线程是t1,t2将等待t1执行结束后才执行。
运行结果如下:

thread t1 is running
thread t1 is over
thread t2 is running
thread t2 is over

此时t1、t2是顺序执行的。

文章转载自: https://blog.youkuaiyun.com/a158123/article/details/78633772

### Java 中 `Thread.join()` 方法详解 `Thread.join()` 是 Java 提供的一个用于线程间协调的方法,它可以让当前线程等待另一个线程完成后再继续执行。具体来说,当调用某个线程的 `join()` 方法时,当前线程会阻塞直到目标线程结束为止。 #### 方法签名 `Thread` 类提供了三种重载形式的 `join()` 方法: 1. **无参数版本** ```java public final void join() throws InterruptedException; ``` 调用此方法会使当前线程一直等待,直到目标线程完全执行完毕[^1]。 2. **带毫秒数参数版本** ```java public final synchronized void join(long millis) throws InterruptedException; ``` 此方法允许设置最大等待时间(单位为毫秒)。如果指定的时间到达而目标线程仍未终止,则当前线程将继续执行。 3. **带毫秒和纳秒参数版本** ```java public final synchronized void join(long millis, int nanos) throws InterruptedException; ``` 这种方式可以更精确地控制超时时间,其中 `nanos` 表示额外的纳秒部分[^1]。 --- #### 使用场景 以下是常见的使用场景及其解释: 1. **确保子线程先于主线程完成** 如果某些资源依赖于子线程的结果,在这种情况下可以通过 `join()` 来保证子线程已经完成了其工作再访问这些共享资源[^2]。 示例代码如下: ```java Thread t = new Thread(() -> { System.out.println("子线程正在运行..."); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子线程已完成"); }); t.start(); try { t.join(); // 主线程在此处等待子线程完成 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("主线程继续执行..."); ``` 2. **限制等待时间** 在实际开发中,有时并不希望无限期地等待某一线程完成。此时可利用带有超时参数的 `join(millis)` 或 `join(millis, nanos)` 实现有限制条件下的等待。 修改上面的例子来展示这一点: ```java Thread t = new Thread(() -> { System.out.println("子线程启动..."); try { Thread.sleep(5000); // 子线程睡眠较长时间 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子线程结束..."); }); t.start(); try { t.join(3000); // 只等待最多三秒钟 } catch (InterruptedException e) { e.printStackTrace(); } if (t.isAlive()) { System.out.println("子线程仍在运行,未等到其完成!"); } else { System.out.println("子线程已成功完成!"); } ``` --- #### 注意事项 1. **抛出异常处理** 调用 `join()` 的时候可能会引发 `InterruptedException` 异常,因此需要将其放在 `try-catch` 块中或者声明由外部捕获。 2. **死锁风险** 不恰当的使用可能导致程序陷入死锁状态。例如两个线程互相调用了对方的 `join()` 方法就会造成循环等待现象。 3. **性能影响** 频繁调用 `join()` 将增加上下文切换开销从而降低整体效率,应谨慎评估是否真的必要采用这种方式来进行同步操作。 --- ### 总结 通过合理运用 `Thread.join()` 方法可以在多线程环境下有效管理各线程之间的顺序关系以及生命周期;然而也要注意潜在的风险并遵循最佳实践原则以构建健壮的应用程序结构[^2]。 ```java public class JoinExample { public static void main(String[] args) throws InterruptedException { Thread childThread = new Thread(() -> { System.out.println(Thread.currentThread().getName() + ": 开始任务..."); try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ": 完成任务..."); }, "Child"); long startTime = System.currentTimeMillis(); childThread.start(); childThread.join(1500); long endTime = System.currentTimeMillis(); System.out.println("Main waited for: " + (endTime - startTime) + " ms."); if(childThread.isAlive()){ System.out.println("Child thread is still alive after timeout!"); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值