开发者

Java - How to know when thread is waiting?

Is there any neat solution of knowing when a thread has been put into wait status? I am putting threads to wait and I notify them when开发者_高级运维 i need it. But sometimes I want to know if a thread is currently waiting, and if so, I have to do something else.

I could probably set a flag myself to true/false. But I can't imagine there is a better way to do this?


The method getState() of a thread returns a Thread.State which can be:

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED

See Thread.State.


Have you looked at Thread.getState?


Check

  • public Thread.State getState()
  • Thread.State.WAITING

Thread.State: Differences between BLOCKED vs WAITING


You can have all info that you want using the ThreadMXBean.

Try this code:

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

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜