确定线程是否正在休眠

时间:2013-03-13 15:16:13

标签: java multithreading

我想知道如何知道线程是否正在休眠。 我搜索了一下,然后收集了一些信息,形成了我写了一个方法 isSleeping():boolean 的信息,我想我可以把它放在一个类中,以确定线程是否正在休眠。我只是想知道我可能错过了什么。注意:我没有经验0天。

//isSleeping returns true if this thread is sleeping and false otherwise.
public boolean isSleeping(){
    boolean state = false;
    StackTraceElement[] threadsStackTrace = this.getStackTrace();

    if(threadsStackTrace.length==0){
        state = false;
    }
    if(threadsStackTrace[0].getClassName().equals("java.lang.Thread")&&
            threadsStackTrace[0].getMethodName().equals("Sleep")){
        state = true;
    }
    return state;
}

3 个答案:

答案 0 :(得分:1)

更改“睡眠” - > “睡觉”。除此之外你不应该在this上使用stacktrace,你的方法应该接受一个Thread参数。考虑一下这个

    Thread t = new Thread(new Runnable(){
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
    Thread.sleep(100);
    if(t.getStackTrace()[0].getClassName().equals("java.lang.Thread")&&
            t.getStackTrace()[0].getMethodName().equals("sleep")){
        System.out.println("sleeping");
    }

输出

sleeping

答案 1 :(得分:0)

您可以查看Thread#getState()是否有TIMED_WAITING州。如果使用这种方法,应注意确保您没有调用Object#wait

答案 2 :(得分:0)

我有这个想法,我没有检查,但我认为它会起作用:

您可以扩展线程并覆盖睡眠以切换状态。 像这样:

 @Override
public static void sleep(long millis, int nanos)
throws InterruptedException {
   SLEEPMARKER = true;
   super.sleep(millis, nanos);
   SLEEPMARKER = false;
}

 @Override
public static void sleep(long millis)
throws InterruptedException {
   SLEEPMARKER = true;
   super.sleep(millis);
   SLEEPMARKER = false;
}

然后你只需要标记和吸气剂。

public static boolean SLEEPMARKER = false;
public static boolean isSleeping(){
   return SLEEPMARKER;
}