多线程高并发学习笔记之关于join()的胡思乱想

引子:在做一道题的时候引发的思考,这道题是这样的:实现一个容器,提供两个方法,add,size写两个线程,线程1添加10个元素到容器中,线程2实现监控元素得个数,当个数到5个时,线程2给出提示并结束

答案有多种,比如说用wait()、notify()来实现,LockSupport的park()、unpark()来实现,其中有一种解题的思路是采用Semaphore来实现。但是Semaphore,realease后无法指定具体哪个线程得到执行权,也就无法保证在线程1数到5个时准确提示,所以需要配合join()来实现,我最开始是这样写的:

public class ThreadLearn04 {
    static Thread t1,t2;
    List<Object> list = Collections.synchronizedList(new ArrayList<>());
    public void add(Object o){list.add(o);}
    public int size(){return list.size();}
    public static void main(String[] args) {
        ThreadLearn04 c = new ThreadLearn04();
        Semaphore s = new Semaphore(1);
        t1=  new Thread(()->{
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 10; i++) {
                if (i==5){
                    s.release();
                    try {
                        t2.start();
                        t2.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                c.add(new Object());
                System.out.println("当前已经加了"+(i+1)+"个了");
            }
        },"t1");

        t2 = new Thread(()->{
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (c.size()==5){
                System.out.println("已经加入5个了,该结束了");
            }
            System.out.println("t2结束");
            s.release();
        },"t2");

        t1.start();
    }
}

大佬们肯定一眼就看出问题了吧,没错,t2线程join()了但是没有start()无法进入running状态,因为在我的潜意识里,只要调用t2.join()方法就会自动启动t2线程,于是我各种查找资料,查join()的实现方式,当点击进入join()方法的时候你会发现他其实底层是采用的wait()方法实现的

    public final void join() throws InterruptedException {
        join(0);
    }
 public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

看到wait(0)了吧,也就是说只要t2线程为运行状态就会一直等待下去,那么又出现了一个新问题,什么时候被唤醒呢,因为不可能只有wait()而没有notify(),不然线程会一直阻塞。最终查到是在JVM的源码中,可以参考这篇文章

// 位于/hotspot/src/share/vm/runtime/thread.cpp中
void JavaThread::exit(bool destroy_vm, ExitType exit_type) {
    // ...

    // Notify waiters on thread object. This has to be done after exit() is called
    // on the thread (if the thread is the last thread in a daemon ThreadGroup the
    // group should have the destroyed bit set before waiters are notified).
    ensure_join(this);
    // ...
}


static void ensure_join(JavaThread* thread) {
    // We do not need to grap the Threads_lock, since we are operating on ourself.
    Handle threadObj(thread, thread->threadObj());
    assert(threadObj.not_null(), "java thread object must exist");
    ObjectLocker lock(threadObj, thread);
    // Ignore pending exception (ThreadDeath), since we are exiting anyway
    thread->clear_pending_exception();
    // Thread is exiting. So set thread_status field in  java.lang.Thread class to TERMINATED.
    java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
    // Clear the native thread instance - this makes isAlive return false and allows the join()
    // to complete once we've done the notify_all below
    java_lang_Thread::set_thread(threadObj(), NULL);
    
    lock.notify_all(thread);

    // Ignore pending exception (ThreadDeath), since we are exiting anyway
    thread->clear_pending_exception();
}

瞧一瞧,看一看,lock.notify_all(thread)没有,也就是线程执行完毕后,将会激活持有thread线程对象锁的线程,那么对应我们写的代码,谁持有了呢,也就是谁调用了join(),谁就持有了加入线程对象锁。t1中调用了t2.join(),也就是t1持有了t2线程对象锁,so,在t2执行完后,jvm将会调用lock.notify_all(thread),唤醒所有持有t2对象锁的所有线程。哎,有点绕口…
然后…查了那么多发现并没有解决自己的疑惑,为啥t2.join()没有自动执行t2线程中的方法。后面才晓得,要调用join()方法,加入的线程必须先start()否则将毫无意义,因为…join()并不会自动调用start(),你线程都还没有启动,join个毛呀…
这里还有个问题,到底在哪儿开启t2,如果在t1外层开启的话就不能保证t2输出的时候t1已经执行到t2.join()了,也就是说很有可能,t2都执行完了,t1才执行到t2.join(),也就毫无意义了。
so,应该直接在join()前一句加就ok了。

                if (i==5){
                    s.release();
                    try {
                        t2.start();
                        t2.join();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

学习笔记,如有不对之处烦请大佬指出,Thanks…

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lordky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值