如果目标尚未启动,那么Java中的Thread.join()的行为是什么?

时间:2021-05-24 20:42:39

In a multi-threaded java program, what happens if a thread object T has been instantiated, and then has T.join() called before the thread has started? Assume that some other thread could call T.start() at any time after T has been instantiated, either before or after another thread calls T.join().

在多线程java程序中,如果一个线程对象T被实例化,然后在线程启动之前调用T.join(),会发生什么?假设其他一些线程可以在实例化T之后的任何时间调用T.start(),或者在另一个线程调用T.join()之前或者之后。

I'm asking because I think I have a problem where T.join() has been called before T.start(), and the thread calling T.join() hangs.

我这样问是因为我认为我有一个问题,在T.start()之前调用了.join(),而调用.join()的线程挂起了。

Yes, I know I have some design problems that, if fixed, could make this a non-issue. However, I would like to know the specifics of the join() behavior, because the only thing the Java API docs say is "Waits for this thread to die."

是的,我知道我有一些设计问题,如果解决了,就不会有问题了。但是,我想知道join()行为的具体情况,因为Java API文档只说“等待这个线程死掉”。

1 个解决方案

#1


12  

It will just return. See code below - isAlive() will be false before the thread starts, so nothing will happen.

它只会返回。请参见下面的代码- isAlive()将在线程开始之前为false,因此不会发生任何事情。

   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;
        }
    }
    }

The code snippet is © Copyright Oracle 2006 and/or its affiliates, and can be found here. Licensed under Java Research License.

甲骨文版权©2006的代码片段和/或其附属公司,并可以在这里找到。获得Java研究许可。

#1


12  

It will just return. See code below - isAlive() will be false before the thread starts, so nothing will happen.

它只会返回。请参见下面的代码- isAlive()将在线程开始之前为false,因此不会发生任何事情。

   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;
        }
    }
    }

The code snippet is © Copyright Oracle 2006 and/or its affiliates, and can be found here. Licensed under Java Research License.

甲骨文版权©2006的代码片段和/或其附属公司,并可以在这里找到。获得Java研究许可。