¿Cómo se determina si un hilo se está ejecutando?En Java, ¿cómo se determina si se está ejecutando un subproceso?
Respuesta
Thread.isAlive()
Comprobar el estado del hilo llamando Thread.isAlive
.
Creo que puede usar GetState(); Puede devolver el estado exacto de un hilo.
Puede utilizar este método:
boolean isAlive()
Devuelve cierto si el hilo está todavía vivo y falsa si el hilo está muerto. Esto no es estático. Necesitas una referencia al objeto de la clase Thread.
Un consejo más: Si está comprobando su estado para que el hilo principal espere mientras el nuevo hilo todavía se está ejecutando, puede usar el método join(). Es más útil
Haga que su hilo notifique algún otro hilo cuando haya terminado. De esta forma, siempre sabrá exactamente qué está pasando.
Para ser precisos,
Thread.isAlive()
devuelve verdadero si se ha iniciado la rosca (aún no estén en marcha), pero aún no ha completado su método run.
Thread.getState()
devuelve el estado exacto del hilo.
Pensado para escribir un código para demostrar las isAlive(), GetState() métodos, este ejemplo controla un hilo todavía termina (muere).
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.State clase enum y el nuevo getState() API se proporcionan para consultar el estado de ejecución de un hilo.
Un subproceso solo puede estar en un estado en un momento determinado. Estos estados son estados de máquina virtual que no reflejan ningún estado de subproceso de sistema operativo [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
].
enum Thread.State se extiende Enum implementa Serializable, Comparable
getState()
jdk5
-public State getState() {...}
«devuelve el estado dethis
hilo. Este método está diseñado para usarse en la supervisión del estado del sistema, no para el control de sincronización.isAlive() -
public final native boolean isAlive();
«devoluciones cierto si el hilo sobre el cual se llama sigue viva, de lo contrario devuelve falso . Un hilo está vivo si se ha iniciado y aún no ha muerto.
Ejemplo de código fuente de las clases java.lang.Thread
y 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;
}
}
}
Ejemplo:
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 también
- 1. ¿Se está ejecutando un subproceso en iOS?
- 2. ¿Cómo se determina si CKEditor está cargado?
- 3. Compruebe si un subproceso de Win32 se está ejecutando o está en estado suspendido
- 4. ¿Cómo se determina si un objeto está bloqueado (sincronizado) para no bloquearlo en Java?
- 5. ¿Se está ejecutando el hilo Java en qué procesador?
- 6. Cómo comprobar si se está ejecutando un Thread de Android
- 7. ¿Cómo verificar si un proceso se está ejecutando con Delphi?
- 8. ¿Cómo saber si se está ejecutando un temporizador?
- 9. ¿Cómo puedo saber si un proceso se está ejecutando?
- 10. Comprobar si el proceso se está ejecutando
- 11. encontrar un trabajo si se está ejecutando en Quartz1.6
- 12. Verifica programáticamente si se está ejecutando syncdb
- 13. comisión si ya se está ejecutando
- 14. ¿Cómo detectar a través de Java si un proceso en particular se está ejecutando en Windows?
- 15. ¿Cómo puede encontrar el número de procesador en el que se está ejecutando un subproceso?
- 16. Comprueba si se está ejecutando un archivo exe específico
- 17. ¿Verifica si se está ejecutando un servicio de Windows?
- 18. Compruebe si un script php todavía se está ejecutando
- 19. Powershell: si un proceso no se está ejecutando, inícielo
- 20. ¿Cómo puedo probar si R se está ejecutando como Rscript?
- 21. OSX: ¿Cómo detectar si se está ejecutando Mission Control?
- 22. Cómo determinar si una aplicación web se está ejecutando actualmente
- 23. ¿Cómo verificar si el servidor X se está ejecutando?
- 24. Cómo saber si el servidor de emacs se está ejecutando
- 25. Cómo rastrear si se está ejecutando una tarea async/awaitable
- 26. ¿Cómo comprobar si una aplicación WPF ya se está ejecutando?
- 27. ¿Cómo saber si la actualización MATERIALIZED VIEW se está ejecutando?
- 28. C# HttpWebRequest - ¿Cómo se determina si se realizó HTTP 301?
- 29. ¿Cómo determinar si el código .NET se está ejecutando en un proceso ASP.NET?
- 30. ¿Cómo puede saber mi programa si Delphi se está ejecutando?
supongo que tiene alguna diferencia con respecto a 'Thread.State.RUNNABLE' (el último parece más fiable) – user924