join方法

在项目实践中经常会遇到一个场景,就是需要等待某几件事情完成后才能继续往下执行,比如多个线程全部加载完毕再汇总处理。

Thread 类中有一个 join 方法可以做这个事情,等待通知方法是 Object 类中的方法,而 join 方法则是 Thread 类直接提供的。join 是无参且返回值为 void 的方法。

public class JoinTest {
    public static void main(String[] args) throws InterruptedException {

        Thread threadOne = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程one执行完毕。。。");
            }
        });

        Thread threadTwo = new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("子线程two执行完毕。。。");
            }
        });

        //启动子线程
        threadOne.start();
        threadTwo.start();
        //等待子线程执行完毕,返回
        threadOne.join();
        threadTwo.join();
        System.out.println("所有子线程执行完毕。。。");
    }
}

线程A调用线程B的 join 方法后会被阻塞,当其他线程调用了线程A的 interrupt() 方法中断了线程A时,线程A会抛出 InterruptedException 异常而返回。

public class JoinInterruptTest {
    public static void main(String[] args) {
        //线程 one
        Thread threadOne = new Thread(new Runnable() {
            public void run() {
                System.out.println("线程 one 开始");
                for (;;){

                }
            }
        });

        //获取主线程
        final Thread mainThread = Thread.currentThread();

        //线程 two
        Thread threadTwo = new Thread(new Runnable() {
            public void run() {
                try {
                    //休眠 1 s
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mainThread.interrupt();
            }
        });

        //启动子线程
        threadOne.start();

        //延迟 1s 启动线程
        threadTwo.start();

        try {
            threadOne.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值