Java에서 스레드가 실행 중인지 어떻게 확인합니까?
스레드가 실행 중인지 어떻게 확인합니까?
Thread.isAlive()
이 방법을 사용할 수 있습니다.
boolean isAlive()
스레드가 아직 살아 있으면 true를 반환하고 스레드가 죽으면 false를 반환합니다. 이것은 정적이 아닙니다. Thread 클래스의 개체에 대한 참조가 필요합니다.
한 가지 더 팁 : 새 스레드가 계속 실행되는 동안 메인 스레드가 대기하도록 상태를 확인하는 경우 join () 메서드를 사용할 수 있습니다. 더 편리합니다.
GetState () 사용할 수 있다고 생각합니다 . 스레드의 정확한 상태를 반환 할 수 있습니다.
을 호출하여 스레드 상태를 확인하십시오 Thread.isAlive
.
정확히 말하면
Thread.isAlive()
스레드가 시작되었지만 (아직 실행 중이 아닐 수도 있음) 실행 메서드가 아직 완료되지 않은 경우 true를 반환합니다.
Thread.getState()
스레드의 정확한 상태를 반환합니다.
Thread.State enum 클래스와 새로운 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();
}
}
}
@또한보십시오
스레드가 완료되면 다른 스레드에 알립니다. 이렇게하면 항상 무슨 일이 일어나고 있는지 정확히 알 수 있습니다.
Thought to write a code to demonstrate the isAlive() , getState() methods, this example monitors a thread still it terminates(dies).
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());
}
}
참고URL : https://stackoverflow.com/questions/861346/in-java-how-do-you-determine-if-a-thread-is-running
'IT TIP' 카테고리의 다른 글
자바 스크립트로 라디오 버튼 확인 (0) | 2020.10.18 |
---|---|
map 및 join을 사용하여 반응 구성 요소를 렌더링하는 방법 (0) | 2020.10.18 |
Java에서 정수를 float로 어떻게 변환 할 수 있습니까? (0) | 2020.10.18 |
'DateTime'이 'Nothing'인지 왜 확인할 수 없습니까? (0) | 2020.10.18 |
Python : 목록에서 첫 번째 문자열의 첫 번째 문자를 얻습니까? (0) | 2020.10.18 |