java多线程join()方法的坑

1、首先来看段代码

public class JoinRelase {

    static Object object = new Object();

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

        for (int i=0; i<2; i++){
            Thread thread = new Thread(new SubThread(), "Daemon Thread!"+i);
            thread.setName("thread-" + i);
            thread.start();
            Thread.sleep(10000);
        }
        System.out.println("主线程结束");
    }

    static class SubThread implements Runnable{

        @SneakyThrows
        @Override
        public void run() {
            synchronized (Thread.currentThread()) {
                System.out.println("获取到锁!!!ThreadName: " + Thread.currentThread().getName());
                Thread.currentThread().join();
            }
        }
    }
}

运行这段代码你会发现,线程运行如下,一直都没有停止
在这里插入图片描述

2、原因分析

join() 这个方法的作用是先将当前线程挂起,待其他线程结束后在执行当前线程的代码。如果调用了Thread.currentThread().join(); 这个方法,那么线程一直在阻塞,无法终止。因为它自己在等待自己结束;这无疑会造成死锁;所以千万不能用Thread.currentThread().join()。当我对上面代码进行如下改造后就可成功运行

public class JoinRelase {

    static Object object = new Object();

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

        for (int i=0; i<2; i++){
            Thread thread = new Thread(new SubThread(), "Daemon Thread!"+i);
            thread.setName("thread-" + i);
            thread.start();
            thread.join();  // 将join放在这里,让主线程来调用
            Thread.sleep(10000);
        }
        System.out.println("主线程结束");
    }

    static class SubThread implements Runnable{

        @SneakyThrows
        @Override
        public void run() {
            synchronized (Thread.currentThread()) {
                System.out.println("获取到锁!!!ThreadName: " + Thread.currentThread().getName());
//                Thread.currentThread().join();
            }
        }
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值