Java - 如何知道线程何时等待?

时间:2009-12-01 11:38:52

标签: java multithreading

知道线程何时进入wait状态是否有任何简洁的解决方案?当我需要它时,我将线程放到wait和我notify。但有时我想知道线程当前是否正在等待,如果是,我必须做其他事情。

我可能会自己设置一个标志为true / false。但我无法想象有更好的方法可以做到这一点吗?

4 个答案:

答案 0 :(得分:39)

线程的方法getState()返回Thread.State,可以是:

NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING或TERMINATED

请参阅Thread.State

答案 1 :(得分:3)

你看过Thread.getState吗?

答案 2 :(得分:3)

答案 3 :(得分:0)

您可以使用ThreadMXBean获取所需的所有信息。

试试这段代码:

package com.secutix.gui.seatmap;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

public class ThreadStatus {

    private static final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            buildAndLaunchThread(i);
        }

        Thread t = new Thread(){

            @Override
            public void run() {
                while(true){
                    printThreadStatus();
                    try {
                        sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        };
        t.setName("detector");
        t.start();

    }

    protected static void printThreadStatus() {
        ThreadInfo[] infos = mbean.dumpAllThreads(true, true);

        for (ThreadInfo threadInfo : infos) {
            System.out.println(threadInfo.getThreadName() + " state = " + threadInfo.getThreadState());
        }

    }

    private static void buildAndLaunchThread(int i) {
        Thread t1 = new Thread(){

            @Override
            public void run() {
                while(true){
                    try {
                        sleep(3000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }

        };
        t1.setName("t" + i);
        t1.start();

    }
}