Si queremos que un thread se detenga, necesitamos influir en su código para que salte al final y termine.
Es habitual utilizar un campo de la clase para marcar la condición “tienes que parar”. La propia clase decide cual es el mejor momento para parar. A veces se denomina “parada ordenada”.
Otra opción es interrumpir el thread. Ver “interrupciones”.
class StoppableRepeater |
public class
StoppableRepeater extends Thread { private String id; private int count; private volatile boolean stop= false; public StoppableRepeater(String id) { this.id = id; this.count = 0; } public void setStop(boolean stop) { this.stop = stop; } public void run() { do { System.out.println(id + ": " + count); count++; try { Thread.sleep(1000); // 1000ms = 1s } catch (InterruptedException ignore) { } } while (!stop); System.out.println(id + ": end"); } } |
class StoppableRepeaters |
public class
StoppableRepeaters { public static void main(String[] args) { StoppableRepeater threadA = new
StoppableRepeater("A"); StoppableRepeater threadB = new StoppableRepeater("B"); threadA.start(); threadB.start(); System.out.println("Repeaters ..."); sleep(2); threadA.setStop(true); sleep(2); threadB.setStop(true); } private static void sleep(int s) { try { Thread.sleep(s * 1000); } catch (InterruptedException ignore) { } } } |
> java StoppableRepeaters |
A: 0 Repeaters ... B: 0 A: 1 B: 1 A: end B: 2 B: 3 B: end |
Temas relacionados