Come si determina se un thread è in esecuzione?In Java, come si determina se un thread è in esecuzione?
risposta
Thread.isAlive()
di controllare lo stato filo chiamando Thread.isAlive
.
Penso che sia possibile utilizzare GetState(); Può restituire lo stato esatto di un thread.
È possibile utilizzare questo metodo:
boolean isAlive()
Restituisce vero se il filo è ancora vivo e falso se il thread è morto. Questo non è statico. È necessario un riferimento all'oggetto della classe Thread.
Un altro consiglio: Se si sta verificando lo stato per far sì che il thread principale aspetti mentre il nuovo thread è ancora in esecuzione, è possibile utilizzare il metodo join(). È più comodo.
Una volta terminato, informare il thread su un altro thread. In questo modo saprai sempre esattamente cosa sta succedendo.
per essere precisi,
Thread.isAlive()
restituisce true se è stato avviato il filo (potrebbe non essere ancora in esecuzione), ma non ha ancora completato il suo metodo run.
Thread.getState()
restituisce lo stato esatto del thread.
pensato di scrivere un codice per illustrare i isAlive(), GetState() metodi, questo esempio controlla un thread ancora terminato (stampi).
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 classe enum e il nuovo getState() API sono fornite per interrogare lo stato di esecuzione di un thread.
Un thread può essere in uno solo stato in un determinato momento. Questi stati sono stati della macchina virtuale che non riflettono gli stati del thread del sistema operativo [NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED
].
enumerazione Thread.State estende Enum implementa Serializable, Comparable
getState()
jdk5
-public State getState() {...}
«restituisce lo statothis
thread. Questo metodo è progettato per l'uso nel monitoraggio dello stato del sistema, non per il controllo della sincronizzazione.isAlive() -
public final native boolean isAlive();
«Returns vero se il filo su cui è chiamato è ancora vivo, altrimenti restituisce falso . Un thread è vivo se è stato avviato e non è ancora morto.
Campione del codice sorgente di classi di java.lang.Thread
e 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;
}
}
}
Esempio:
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 anche
- 1. uccidere un thread in esecuzione in java?
- 2. Determina se l'app è in esecuzione o no
- 3. Come verificare se un thread è in esecuzione nel pool di thread ExecutorService
- 4. LDAP Java - Determina se l'utente in un determinato gruppo?
- 5. Come si verifica se R è in esecuzione come Rscript?
- 6. Determina se un file è aperto
- 7. Determina se un websocket send() è finito
- 8. Come si elimina un thread da un altro thread in Java?
- 9. Determina se un file è realmente un'immagine in express/node.js
- 10. Determina se una sottoview è visibile in un UIScrollView
- 11. Come si determina se un indirizzo IP è privato, in Python?
- 12. Elasticsearch troppe thread in esecuzione
- 13. Come verificare se un thread è già stato avviato o meno in Java?
- 14. Python: il thread è ancora in esecuzione
- 15. Come scoprire se un processo è in esecuzione in C?
- 16. Determina se un'applicazione è in esecuzione in primo piano quando viene ricevuta una notifica su iOS
- 17. Determina se WindowServer è disponibile?
- 18. Come si determina su quale monitor è in esecuzione il programma .NET Windows Forms?
- 19. Determina se LTE è attivato?
- 20. Come si determina se un inserimento o un aggiornamento ha avuto successo utilizzando Java e MySQL?
- 21. C++ determina se la classe è paragonabile
- 22. Determina se un'immagine è in scala di grigi in Matlab
- 23. Determina se l'oggetto è intero
- 24. Come controllare se l'applicazione è in esecuzione
- 25. Come accedere a un metodo da un altro thread in esecuzione in java
- 26. Come sapere se un MediaRecorder è in esecuzione o no?
- 27. Come posso determinare su quale core è in esecuzione un thread Java?
- 28. In Java se un thread è stato ucciso, cosa succederà all'altro thread?
- 29. Come rilevare tramite Java se un particolare processo è in esecuzione in Windows?
- 30. Come verificare se un thread è finito in Rust?
Credo che abbia qualche differenza da 'Thread.State.RUNNABLE' (l'ultima sembra più affidabile) – user924