My teacher told me not to use stop() but to use this way in the Thread class:
public void pararHilo() {
stopHilo = true;
}
public void run() {
while (!stopHilo)
c++;
}
As far as I know, when pararHilo() is called the loop ends, therefore it exits the run() method and the Thread dies. The thing is that I have a pretty decent laptop and when doing tests with this code (here and at school) my machine gets laggy as hell and I have to close Eclipse... Am I missing something?
Whole code
public class EjemploHilo {
public static void main(String args[]) {
HiloPrioridad h1 = new HiloPrioridad();
HiloPrioridad h2 = new HiloPrioridad();
HiloPrioridad h3 = new HiloPrioridad();
//el hilo con mas prioridad contara mas deprisa que los demas
h1.setPriority(Thread.MAX_PRIORITY);
h2.setPriority(Thread.NORM_PRIORITY);
h3.setPriority (Thread.MIN_PRIORITY);
h1.start(); h2.start(); h3.start();
try {
Thread.sleep(2000);
} catch (Exception e) { }
h1.pararHilo();
h2.pararHilo();
h3.pararHilo();
System.out.println("h1 (Prioridad Maxima): " + h1.getContador());
System.out.println("h2 (Prioridad Normal): " + h2.getContador());
System.out.println("h3 (Prioridad Minima): " + h3.getContador());
}
}
public class HiloPrioridad extends Thread {
private int c = 0;
private boolean stopHilo= false;
public int getContador() {
return c;
}
public void pararHilo() {
stopHilo = true;
}
public void run() {
while (!stopHilo)
c++;
}
}