Terminar un hilo (bucle) usando otro hilo
Frecuentes
Visto 279 veces
0
Estoy tratando de encontrar una manera de terminar un hilo que actualmente tiene un bucle infinito. Con mi experiencia traté de crear un segundo subproceso que interrumpiría el primero que se repite infinitamente, pero, por supuesto, debido al bucle infinito ... el primer subproceso nunca alcanzaría la función de suspensión. Así que ahora estoy de vuelta a esto
public class Pulse{
private static int z = 0;
public static void main( String[] args ) throws Exception {
try {
final long stop=System.currentTimeMillis()+5L;
//Creating the 2 threads
for (int i=0; i<2; i++) {
final String id=""+i+": ";
new Thread(new Runnable() {
public void run() {
System.err.println("Started thread "+id);
try{
while ( System.currentTimeMillis() < stop ) {
//Purposely looping infinite
while(true){
z++;
System.out.println(z);
}
}
} catch (Exception e) {
System.err.println(e);
}
}
}).start();
}
} catch (Exception x) {
x.printStackTrace();
}
}
}
4 Respuestas
2
Tener un volatile boolean
campo, decir running
. Hazlo true
. Donde tienes while (true)
cambia eso a while (running)
y while ( System.currentTimeMillis() < stop ) {
a while (running && ( System.currentTimeMillis() < stop) ) {
. Ahora, cambia running
a false
de algún otro hilo. Eso debería detener el ciclo bastante bien.
contestado el 03 de mayo de 12 a las 15:05
1
Puedes cambiar
while(true){
a
while(!Thread.currentThread().isInterrupted()){ //or Thread.interrupted()
Ahora, cuando interrumpa el hilo, debería salir correctamente del bucle infinito.
contestado el 03 de mayo de 12 a las 15:05
1
Tendrá que hacer una llamada Thread.interrupted() dentro del ciclo para verificar si se ha interrumpido y manejarlo adecuadamente. O while(!Thread.interrupted()) en su lugar.
contestado el 03 de mayo de 12 a las 15:05
1
Tienes que hacer algo como esto:
public class ThreadStopExample {
public static volatile boolean terminate = false;
public static void main(String[] args) {
new Thread(new Runnable() {
private int i;
public void run() {
while (!terminate) {
System.out.println(i++);
}
System.out.println("terminated");
}
}).start();
// spend some time in another thread
for (int i = 0; i < 10000; i++) {
System.out.println("\t" + i);
}
// then terminate the thread above
terminate = true;
}
}
contestado el 03 de mayo de 12 a las 15:05
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas java multithreading infinite-loop or haz tu propia pregunta.
Parece que esto podría ser un engaño de varios... un ejemplo es: stackoverflow.com/questions/4472611/… - la parte 'usando otro hilo' es el rey de lo implícito. - Doug Moscrop