[英]In Java, how do you determine if a thread is running?
你如何確定一個線程是否正在運行?
Thread.isAlive()
您可以使用此方法:
boolean isAlive()
如果線程還活着,則返回 true,如果線程已死,則返回 false。 這不是靜態的。 您需要對 Thread 類的對象的引用。
另一個提示:如果您正在檢查它的狀態以使主線程在新線程仍在運行時等待,則可以使用 join() 方法。 它更方便。
我認為你可以使用GetState() ; 它可以返回線程的確切狀態。
通過調用Thread.isAlive
檢查線程狀態。
准確地說,
如果線程已啟動(可能尚未運行)但尚未完成其 run 方法,則Thread.isAlive()
返回 true。
Thread.getState()
返回線程的確切狀態。
Thread.State枚舉類和新的getState() API 用於查詢線程的執行狀態。
一個線程在給定的時間點只能處於一種狀態。 這些狀態是虛擬機狀態,不反映任何操作系統線程狀態[ NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
]。
enum Thread.State擴展了 Enum 實現了Serializable , Comparable
getState() jdk5
- public State getState() {...}
«返回this
線程的狀態。 此方法設計用於監視系統狀態,而不是用於同步控制。
isAlive() - public final native boolean isAlive();
«如果在調用它的線程還活着返回true,否則返回false。 如果線程已啟動且尚未死亡,則該線程處於活動狀態。
類java.lang.Thread
和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;
}
}
}
示例以java.util.concurrent.CountDownLatch
並行執行多個線程,完成所有線程后主線程執行。 (直到並行線程完成它們的任務,主線程才會被阻塞。)
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();
}
}
}
@也可以看看
讓您的線程在完成時通知其他線程。 這樣,您將始終確切地知道發生了什么。
想寫一個代碼來演示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());
}
}
您可以使用: Thread.currentThread().isAlive();
. 如果此線程處於活動狀態,則返回true ; 否則為假。
使用Thread.currentThread().isAlive()查看線程是否處於活動狀態[輸出應該為 true] 這意味着線程仍在運行 run() 方法內的代碼或使用Thread.currentThread.getState()方法獲取線程的確切狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.