Java - How to know when thread is waiting?

孤街浪徒 提交于 2019-12-21 03:12:38

问题


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?


回答1:


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

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED

See Thread.State.




回答2:


Have you looked at Thread.getState?




回答3:


Check

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

Thread.State: Differences between BLOCKED vs WAITING




回答4:


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

    }
}


来源:https://stackoverflow.com/questions/1825623/java-how-to-know-when-thread-is-waiting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!