views:

283

answers:

4

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?

+4  A: 

Have you looked at Thread.getState?

Konamiman
+12  A: 

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

NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING or TERMINATED

See Thread.State.

alexander.egger
It is Thread.State instead of Thread.Status
JuanZe
Thanks a lot. Can't believe i missed that!
Stefan Hendriks
@JuanZe Thanks corrected that mistake.
alexander.egger
Of course, by the time the method has returned the state may have changed.
Tom Hawtin - tackline
A: 

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

    }
}
Laurent K