How do you determine if a thread is running?
如何确定线程是否正在运行?
8 个解决方案
#1
74
Thread.isAlive()
Thread.isAlive()
#2
24
You can use this method:
你可以使用这个方法:
boolean isAlive()
It returns true if the thread is still alive and false if the Thread is dead. This is not static. You need a reference to the object of the Thread class.
如果线程仍然存活,则返回true;如果线程已死,则返回false。这不是静态的。您需要对Thread类的对象的引用。
One more tip: If you're checking it's status to make the main thread wait while the new thread is still running, you may use join() method. It is more handy.
还有一个提示:如果您正在检查在新线程仍在运行时让主线程等待的状态,您可以使用join()方法。它更方便。
#3
11
I think you can use GetState(); It can return the exact state of a thread.
我认为可以使用GetState();它可以返回线程的确切状态。
#4
7
Check the thread status by calling Thread.isAlive
.
通过调用thread . isalive来检查线程状态。
#5
3
To be precise,
更精确地说,
Thread.isAlive()
returns true if the thread has been started (may not yet be running) but has not yet completed its run method.
如果线程已经启动(可能还没有运行)但还没有完成其运行方法,那么thread . isalive()将返回true。
Thread.getState()
returns the exact state of the thread.
getstate()返回线程的确切状态。
#6
2
Have your thread notify some other thread when it’s finished. This way you’ll always know exactly what’s going on.
让你的线程在其他线程完成时通知它。这样你就能知道到底发生了什么。
#7
1
Thought to write a code to demonstrate the isAlive() , getState() methods, this example monitors a thread still it terminates(dies).
为了编写代码来演示isAlive()、getState()方法,本示例监视一个线程,该线程仍然终止(终止)。
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's 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());
}
}
#8
0
Thread.State enum class and the new getState() API are provided for querying the execution state of a thread.
线程。为查询线程的执行状态提供了State enum类和新的getState() API。
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
].
线程在给定的时间点上只能处于一种状态。这些状态是虚拟机状态,不反映任何操作系统线程状态[新的、可运行的、阻塞的、等待的、TIMED_WAITING、终止的]。
enum Thread.State extends Enum implements Serializable, Comparable
枚举线程。状态扩展枚举实现可序列化的、可比较的
-
getState()
jdk5
-public State getState() {...}
« Returns the state ofthis
thread. This method is designed for use in monitoring of the system state, not for synchronization control.getState()jdk5 - public State getState(){…}«返回这个线程的状态。这种方法用于监视系统状态,而不是用于同步控制。
-
isAlive() -
public final native boolean isAlive();
« Returns true if the thread upon which it is called is still alive, otherwise it returns false. A thread is alive if it has been started and has not yet died.公共最终布尔值isAlive();如果调用它的线程仍然是活动的,则返回true,否则返回false。如果一个线程已经启动并且还没有死,那么它就是活的。
Sample Source Code's of classes java.lang.Thread
and sun.misc.VM
.
示例源代码的类java.lang。线程和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:
例子:
public class WorkerThreadsWait {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("ThreadGroup1");
CountDownLatch latch = new CountDownLatch(1);
MyThread runnableTarget1 = new MyThread(latch, 5);
Thread thread = new Thread(group, runnableTarget1, "Thread_1");
thread.start();
MyThread runnableTarget2 = new MyThread(latch, 50);
Thread thread2 = new Thread(group, runnableTarget2, "Thread_2");
thread2.start();
thread2.setPriority( Thread.MIN_PRIORITY );
MyThread runnableTarget3 = new MyThread(latch, 50);
Thread thread3 = new Thread(group, runnableTarget3, "Thread_3");
thread3.start();
thread3.setPriority( Thread.MAX_PRIORITY );
System.out.println("main Tread Execution started.");
for (int i = 0; i < 10; i++) {
System.out.println("Main \t : "+i);
if( i == 2 ) {
latch.countDown(); //This will inform all the waiting threads to start
sleepThread( 1 );
}
}
try {
State state = thread.getState();
boolean alive = thread.isAlive();
System.out.format("State : %s, IsAlive: %b \n", state, alive);
if( alive ) {
System.out.println(" => Thread has started. So, joining it to main thread.");
thread.join();
System.out.println("Main Thread waits till the Joined thread's to treminate ('not-alive').");
sleepThread( 1 );
group.stop();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread Execution completed.");
}
static void sleepThread(int sec) {
try {
Thread.sleep( 1000 * sec );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread implements Runnable {
CountDownLatch latch;
int repeatCount;
public MyThread(CountDownLatch latch, int repeatCount) {
this.latch = latch;
this.repeatCount = repeatCount;
}
@Override
public void run() {
try {
String name = Thread.currentThread().getName();
System.out.println("@@@@@ Thread : "+name+" started");
latch.await(); //The thread keeps waiting till it is informed.
System.out.println("@@@@@ Thread : "+name+" notified");
for (int i = 0; i < repeatCount; i++) {
WorkerThreadsWait.sleepThread( 1 );
System.out.println("\t "+ name +": "+i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@See also
@See也
- “implements Runnable” vs. “extends Thread”
- “实现Runnable”与“扩展线程”
- Thread States
- 线程状态
- Thread States Diagram
- 线程状态图
- How to start two threads at “exactly” the same time
- 如何同时启动两个线程
#1
74
Thread.isAlive()
Thread.isAlive()
#2
24
You can use this method:
你可以使用这个方法:
boolean isAlive()
It returns true if the thread is still alive and false if the Thread is dead. This is not static. You need a reference to the object of the Thread class.
如果线程仍然存活,则返回true;如果线程已死,则返回false。这不是静态的。您需要对Thread类的对象的引用。
One more tip: If you're checking it's status to make the main thread wait while the new thread is still running, you may use join() method. It is more handy.
还有一个提示:如果您正在检查在新线程仍在运行时让主线程等待的状态,您可以使用join()方法。它更方便。
#3
11
I think you can use GetState(); It can return the exact state of a thread.
我认为可以使用GetState();它可以返回线程的确切状态。
#4
7
Check the thread status by calling Thread.isAlive
.
通过调用thread . isalive来检查线程状态。
#5
3
To be precise,
更精确地说,
Thread.isAlive()
returns true if the thread has been started (may not yet be running) but has not yet completed its run method.
如果线程已经启动(可能还没有运行)但还没有完成其运行方法,那么thread . isalive()将返回true。
Thread.getState()
returns the exact state of the thread.
getstate()返回线程的确切状态。
#6
2
Have your thread notify some other thread when it’s finished. This way you’ll always know exactly what’s going on.
让你的线程在其他线程完成时通知它。这样你就能知道到底发生了什么。
#7
1
Thought to write a code to demonstrate the isAlive() , getState() methods, this example monitors a thread still it terminates(dies).
为了编写代码来演示isAlive()、getState()方法,本示例监视一个线程,该线程仍然终止(终止)。
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's 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());
}
}
#8
0
Thread.State enum class and the new getState() API are provided for querying the execution state of a thread.
线程。为查询线程的执行状态提供了State enum类和新的getState() API。
A thread can be in only one state at a given point in time. These states are virtual machine states which do not reflect any operating system thread states [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
].
线程在给定的时间点上只能处于一种状态。这些状态是虚拟机状态,不反映任何操作系统线程状态[新的、可运行的、阻塞的、等待的、TIMED_WAITING、终止的]。
enum Thread.State extends Enum implements Serializable, Comparable
枚举线程。状态扩展枚举实现可序列化的、可比较的
-
getState()
jdk5
-public State getState() {...}
« Returns the state ofthis
thread. This method is designed for use in monitoring of the system state, not for synchronization control.getState()jdk5 - public State getState(){…}«返回这个线程的状态。这种方法用于监视系统状态,而不是用于同步控制。
-
isAlive() -
public final native boolean isAlive();
« Returns true if the thread upon which it is called is still alive, otherwise it returns false. A thread is alive if it has been started and has not yet died.公共最终布尔值isAlive();如果调用它的线程仍然是活动的,则返回true,否则返回false。如果一个线程已经启动并且还没有死,那么它就是活的。
Sample Source Code's of classes java.lang.Thread
and sun.misc.VM
.
示例源代码的类java.lang。线程和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:
例子:
public class WorkerThreadsWait {
public static void main(String[] args) {
ThreadGroup group = new ThreadGroup("ThreadGroup1");
CountDownLatch latch = new CountDownLatch(1);
MyThread runnableTarget1 = new MyThread(latch, 5);
Thread thread = new Thread(group, runnableTarget1, "Thread_1");
thread.start();
MyThread runnableTarget2 = new MyThread(latch, 50);
Thread thread2 = new Thread(group, runnableTarget2, "Thread_2");
thread2.start();
thread2.setPriority( Thread.MIN_PRIORITY );
MyThread runnableTarget3 = new MyThread(latch, 50);
Thread thread3 = new Thread(group, runnableTarget3, "Thread_3");
thread3.start();
thread3.setPriority( Thread.MAX_PRIORITY );
System.out.println("main Tread Execution started.");
for (int i = 0; i < 10; i++) {
System.out.println("Main \t : "+i);
if( i == 2 ) {
latch.countDown(); //This will inform all the waiting threads to start
sleepThread( 1 );
}
}
try {
State state = thread.getState();
boolean alive = thread.isAlive();
System.out.format("State : %s, IsAlive: %b \n", state, alive);
if( alive ) {
System.out.println(" => Thread has started. So, joining it to main thread.");
thread.join();
System.out.println("Main Thread waits till the Joined thread's to treminate ('not-alive').");
sleepThread( 1 );
group.stop();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main Thread Execution completed.");
}
static void sleepThread(int sec) {
try {
Thread.sleep( 1000 * sec );
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyThread implements Runnable {
CountDownLatch latch;
int repeatCount;
public MyThread(CountDownLatch latch, int repeatCount) {
this.latch = latch;
this.repeatCount = repeatCount;
}
@Override
public void run() {
try {
String name = Thread.currentThread().getName();
System.out.println("@@@@@ Thread : "+name+" started");
latch.await(); //The thread keeps waiting till it is informed.
System.out.println("@@@@@ Thread : "+name+" notified");
for (int i = 0; i < repeatCount; i++) {
WorkerThreadsWait.sleepThread( 1 );
System.out.println("\t "+ name +": "+i);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@See also
@See也
- “implements Runnable” vs. “extends Thread”
- “实现Runnable”与“扩展线程”
- Thread States
- 线程状态
- Thread States Diagram
- 线程状态图
- How to start two threads at “exactly” the same time
- 如何同时启动两个线程