In Java, how do you determine if a thread is working?

How do you determine if a thread is working?

+68
java multithreading
May 14, '09 at 2:57
source share
8 answers

Thread.isAlive()

+80
May 14, '09 at 3:00 a.m.
source share
β€” -

You can use this method:

 boolean isAlive() 

It returns true if the stream is still alive and false if the stream is dead. This is not static. You need a reference to an object of class Thread.

One more tip: If you check the status so that the main thread continues to wait while the new thread is still running, you can use the join () method. It is more convenient.

+27
May 14 '09 at 3:21
source share

I think you can use GetState () ; It can return the exact state of the stream.

+17
May 14, '09 at 3:12
source share

Check the thread status by calling Thread.isAlive .

+8
May 14 '09 at 3:06
source share

To be precise,

Thread.isAlive() returns true if the thread was started (perhaps not yet started) but has not yet completed its execution method.

Thread.getState() returns the exact state of the thread.

+5
Sep 22 '17 at 14:26
source share

The enum Thread.State class and the new getState () API are designed to request thread execution status.

A thread can only be in one state at a time. These states are virtual machine states that do not reflect the state of the operating system threads [ NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED ].

enum Thread.State extends Enum implements Serializable , Comparable

  • getState () jdk5 - public State getState() {...} " Returns the state of this stream. This method is intended for use in monitoring the state of the system, and not for controlling synchronization.

  • isAlive () - public final native boolean isAlive(); " Returns true if the thread for which it is called is still alive, otherwise it returns false . The thread is alive if it was started and has not yet died.

Sample source code for java.lang.Thread and sun.misc.VM

 package java.lang; public class Thread implements Runnable { public final native boolean isAlive(); // Java thread status value zero corresponds to state "NEW" - 'not yet started'. private volatile int threadStatus = 0; public enum State { NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED; } public State getState() { return sun.misc.VM.toThreadState(threadStatus); } } package sun.misc; public class VM { // ... public static Thread.State toThreadState(int threadStatus) { if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) { return Thread.State.RUNNABLE; } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) { return Thread.State.BLOCKED; } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) { return Thread.State.WAITING; } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) { return Thread.State.TIMED_WAITING; } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) { return Thread.State.TERMINATED; } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) { return Thread.State.NEW; } else { return Thread.State.RUNNABLE; } } } 



Example with java.util.concurrent.CountDownLatch for parallel execution of several threads. After all threads have completed, the main thread is executed. (until the parallel threads complete their task, the main thread will be blocked.)

 public class MainThread_Wait_TillWorkerThreadsComplete { public static void main(String[] args) throws InterruptedException { System.out.println("Main Thread Started..."); // countDown() should be called 4 time to make count 0. So, that await() will release the blocking threads. int latchGroupCount = 4; CountDownLatch latch = new CountDownLatch(latchGroupCount); new Thread(new Task(2, latch), "T1").start(); new Thread(new Task(7, latch), "T2").start(); new Thread(new Task(5, latch), "T3").start(); new Thread(new Task(4, latch), "T4").start(); //latch.countDown(); // Decrements the count of the latch group. // await() method block until the current count reaches to zero latch.await(); // block until latchGroupCount is 0 System.out.println("Main Thread completed."); } } class Task extends Thread { CountDownLatch latch; int iterations = 10; public Task(int iterations, CountDownLatch latch) { this.iterations = iterations; this.latch = latch; } @Override public void run() { String threadName = Thread.currentThread().getName(); System.out.println(threadName + " : Started Task..."); for (int i = 0; i < iterations; i++) { System.out.println(threadName + " : "+ i); sleep(1); } System.out.println(threadName + " : Completed Task"); latch.countDown(); // Decrements the count of the latch, } public void sleep(int sec) { try { Thread.sleep(1000 * sec); } catch (InterruptedException e) { e.printStackTrace(); } } } 

@See also

  • implements runnable versus extends thread
  • Stream states
  • Flow state diagram
  • How to start two threads at the same time
+4
Jan 09 '18 at 11:09
source share

Ask your thread to tell some other thread when it has finished. That way, you always know exactly what is going on.

+2
May 14 '09 at 7:03 a.m.
source share

Thought to write code to demonstrate the isAlive (), getState () methods, this example controls a thread that is still terminating (dying).

 package Threads; import java.util.concurrent.TimeUnit; public class ThreadRunning { static class MyRunnable implements Runnable { private void method1() { for(int i=0;i<3;i++){ try{ TimeUnit.SECONDS.sleep(1); }catch(InterruptedException ex){} method2(); } System.out.println("Existing Method1"); } private void method2() { for(int i=0;i<2;i++){ try{ TimeUnit.SECONDS.sleep(1); }catch(InterruptedException ex){} method3(); } System.out.println("Existing Method2"); } private void method3() { for(int i=0;i<1;i++){ try{ TimeUnit.SECONDS.sleep(1); }catch(InterruptedException ex){} } System.out.println("Existing Method3"); } public void run(){ method1(); } } public static void main(String[] args) { MyRunnable runMe=new MyRunnable(); Thread aThread=new Thread(runMe,"Thread A"); aThread.start(); monitorThread(aThread); } public static void monitorThread(Thread monitorMe) { while(monitorMe.isAlive()) { try{ StackTraceElement[] threadStacktrace=monitorMe.getStackTrace(); System.out.println(monitorMe.getName() +" is Alive and it state ="+monitorMe.getState()+" || Execution is in method : ("+threadStacktrace[0].getClassName()+"::"+threadStacktrace[0].getMethodName()+") @line"+threadStacktrace[0].getLineNumber()); TimeUnit.MILLISECONDS.sleep(700); }catch(Exception ex){} /* since threadStacktrace may be empty upon reference since Thread A may be terminated after the monitorMe.getStackTrace(); call*/ } System.out.println(monitorMe.getName()+" is dead and its state ="+monitorMe.getState()); } } 
+1
Sep 22 '17 at 17:51 on
source share



All Articles