超时的 join 调用后 Java 线程会发生什么 [英] What happens to Java thread after a join call with timeout

查看:70
本文介绍了超时的 join 调用后 Java 线程会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用超时值调用join后Java线程处于什么状态,超时过去了.例如,您有以下代码:

What state is a Java thread in after you call join with a timeout value, and the timeout passes. So for instance you have the following code:

Thread thread = new Thread();
thread.start();
thread.join(TIMEOUT);

并且超时过去了,线程还没有返回什么状态?我需要注意什么以确保我不会泄漏线程.我最初的假设是在 join 调用后执行以下操作:

and the timeout passes and the thread hasn't returned what is the state? What do I need to be aware of to make sure I don't leak threads. My initial assumption is that after the join call doing something like:

if (thread.isAlive())
{
   thread.interrupt();
   thread = null;
}

检查线程是否仍在运行,如果是,则中断它,然后将其清零以确保它被垃圾收集.

To check if the thread is still running and if so interrupt it, and then null it out to make sure it gets garbage collected.

推荐答案

Javadoc 声明 join(time) 函数最多等待多少毫秒,直到线程死亡.实际上,如果超时通过,您的代码将停止阻塞并继续.如果您担心在这种情况下泄漏线程",您可能应该重新设计,这样您就不必加入线程并可以观察正在运行的线程的状态.此外,在线程上调用中断很糟糕.

The Javadoc states that the join(time) function will wait at most that many milliseconds for the thread to die. In effect if the timeout passes your code will stop blocking and continue on. If you are worried about 'leaking threads' in this case you probably should redesign so that you don't have to join the thread and can observe the state of the running thread. Furthermore calling an interrupt on the thread is bad mojo.

class MyThread extends Thread {
    private boolean keepRunning = true;
    private String currentStatus = "Not Running";
    public void run() {
        currentStatus = "Executing"
        while(keepRunning)
        {
           try {
               someTask()
               currentStatus = "Done";
           } catch (Exception e) {
               currentStatus = "task failed";
               keepRunning = false;
           }
        }
    }

    public stopThread() {
       keepRunning = false;
    }
}

以上可能是一个更好的例子来处理线程.您不需要将线程显式设置为 null,但例如,如果您将线程存储在 ArrayList 中,请将其从列表中删除并让 Java 处理它.

Above might be a better example to work off of to work with threads. You need not set the thread to null explicitly, but for example if you're storing threads in an ArrayList remove it from the list and let Java handle it.

这篇关于超时的 join 调用后 Java 线程会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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