如果目标尚未启动,则Thread.join()在Java中的行为是什么? [英] What is the behavior of Thread.join() in Java if the target has not yet started?

查看:78
本文介绍了如果目标尚未启动,则Thread.join()在Java中的行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多线程Java程序中,如果实例化了线程对象T,然后在线程启动之前调用了T.join()会发生什么?假定在实例化T之后的任何时候,其他任何线程都可以在另一个线程调用T.join()之前或之后调用T.start().

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().

我问是因为我认为我有一个问题,其中T.join()在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.

是的,我知道我有一些设计问题,如果解决这些问题,可能会使其不成问题.但是,我想知道join()行为的细节,因为Java API文档唯一说的是等待该线程死亡."

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."

推荐答案

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

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

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

该代码段是©版权所有Oracle 2006和/或其分支机构,可以在此处找到.已获得 Java研究许可的许可.

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

这篇关于如果目标尚未启动,则Thread.join()在Java中的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆