java 如何检查线程是否正在休眠?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5336299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:41:56  来源:igfitidea点击:

How to check if a thread is sleeping?

javamultithreadingsleep

提问by Sameek Mishra

Is there any way to check if a given thread is sleeping?

有没有办法检查给定的线程是否正在休眠?

回答by Joachim Sauer

You can call Thread.getState()on and check if the state is TIMED_WAITING.

您可以致电Thread.getState()并检查状态是否为TIMED_WAITING

Note, however that TIMED_WAITINGdoesn't necessarily mean that the thread called sleep(), it could also be waiting in a Object.wait(long)call or something similar.

请注意,但这TIMED_WAITING并不一定意味着调用的线程sleep(),它也可能正在等待Object.wait(long)调用或类似的东西。

回答by aioobe

Here is an fairly ugly hack to check if the other thread is sleeping:

这是一个相当丑陋的 hack 来检查另一个线程是否正在休眠:

public static boolean isSleeping(Thread t) {
    StackTraceElement[] ste = t.getStackTrace();

    if (ste.length == 0)
        return false;     // thread has terminated!

    return ste[0].getClassName().equals("java.lang.Thread")
        && ste[0].getMethodName().equals("sleep");
}

回答by add9

i didn't actually did it , but there's an ThreadMXBean Interfacefor getting thread Info

我实际上并没有这样做,但是有一个用于获取线程信息的 ThreadMXBean 接口

which returns ThreadInfo Class, there you might get something with getWaitedTime method.

它返回ThreadInfo Class,在那里你可能会得到一些 getWaitedTime 方法。

回答by Tunca Ersoy

I am not sure if there is a better way but you could change a variable when a thread goes to sleep and check that variable if the thread is sleeping or not.

我不确定是否有更好的方法,但是您可以在线程进入睡眠状态时更改变量,并检查该线程是否处于睡眠状态。

回答by Winfred

You could create your own sleepmethod which records the Thread's IDto a global variableand use it as reference for sleeping thread.

您可以创建自己的sleep方法,该方法将线程的 ID记录到全局变量中,并将其用作睡眠线程的参考。

There's no other way you can tell if a thread is precisely sleeping.

没有其他方法可以判断线程是否正好处于休眠状态。

Hope the three linksbelow help:

希望以下三个链接有帮助: