Java에서는 스레드가 실행 중인지 어떻게 판단합니까?
스레드가 실행 중인지 확인하려면 어떻게 해야 합니까?
Thread.isAlive()
다음 방법을 사용할 수 있습니다.
boolean isAlive()
스레드가 아직 활성 상태이면 true를 반환하고 비활성 상태이면 false를 반환합니다.이건 정전기 아니에요.스레드 클래스의 오브젝트에 대한 참조가 필요합니다.
힌트 하나 더:새 스레드가 실행 중일 때 메인 스레드가 대기하도록 상태를 체크하는 경우 join() 메서드를 사용할 수 있습니다.그게 더 편해요.
GetState()를 사용하면 스레드의 정확한 상태를 반환할 수 있습니다.
호출로 스레드 상태를 확인합니다.Thread.isAlive
.
정확히 말하면
Thread.isAlive()
스레드가 시작되었지만(아직 실행 중이 아닐 수 있음) 실행 메서드가 완료되지 않은 경우 true를 반환합니다.
Thread.getState()
스레드의 정확한 상태를 반환합니다.
스레드.스테이트 열거 클래스와 새로운 getState() API는 스레드 실행 상태를 쿼리하기 위해 제공됩니다.
스레드는 특정 시점에 하나의 상태만 가질 수 있습니다. 이러한 상태는 운영 체제 스레드 상태를 반영하지 않는 가상 시스템 상태입니다.NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
].
getState()
jdk5
-public State getState() {...}
«상태를 반환합니다.this
실.이 방법은 동기화 제어가 아닌 시스템 상태 모니터링에 사용하도록 설계되었습니다.isAlive() -
public final native boolean isAlive();
«호출된 스레드가 아직 활성 상태이면 true를 반환하고 그렇지 않으면 false를 반환합니다.스레드가 시작되었지만 아직 끊어지지 않은 경우 스레드는 활성 상태입니다.
소스 코드 클래스 및 샘플.
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();
}
}
}
@「」도 참조해 주세요.
스레드가 완료되면 다른 스레드에 알립니다.이렇게 하면 무슨 일이 일어나고 있는지 항상 정확히 알 수 있을 거야.
Thread.current 사용스레드().isAlive()는 스레드가 활성[출력] 상태인지 여부를 확인합니다.이것은 스레드가 run() 메서드 내에서 코드를 실행 중인지 또는 Thread.current를 사용하는 것을 의미합니다.스레드.getState() 메서드를 사용하여 스레드의 정확한 상태를 가져옵니다.
이 예에서는 isAlive() 메서드, getState() 메서드를 나타내는 코드를 작성하는 것으로 생각되며, 스레드가 종료(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());
}
}
다음과 같습니다.Thread.currentThread().isAlive();
. 이 스레드가 활성 상태이면 true를 반환하고 그렇지 않으면 false를 반환합니다.
언급URL : https://stackoverflow.com/questions/861346/in-java-how-do-you-determine-if-a-thread-is-running
'sourcecode' 카테고리의 다른 글
Vue/Nuxt 비동기 메타 태그 생성 (0) | 2022.09.03 |
---|---|
express 및 vue js를 사용하여 로그인 성공 후 특정 페이지로 리디렉션하는 방법 (0) | 2022.09.03 |
컴포넌트로 랩된html을 캡처하여 vue.js의 데이터 값을 설정합니다. (0) | 2022.09.03 |
"MVC"의 "컨트롤러"에 들어가는 내용은 무엇입니까? (0) | 2022.08.31 |
Linux에서의 낮은 memcpy 퍼포먼스 (0) | 2022.08.31 |