我的老师告诉我不要使用 stop() 而是在 Thread 类中使用这种方式:
public void pararHilo() {
stopHilo = true;
}
public void run() {
while (!stopHilo)
c++;
}
据我所知,当调用 pararHilo() 时,循环结束,因此它退出 run() 方法并且线程死亡。 问题是,我有一台相当不错的笔记本电脑,当使用此代码(在这里和在学校)进行测试时,我的机器变得非常滞后,我必须关闭 Eclipse...我错过了什么吗?
完整代码
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++;
}
}
最佳答案
您的 while 循环应检查以下内容:
while (!Thread.currentThread().isInterrupted() && /* more work to do */) {
// do more work
}
这样,客户端就可以调用Thread.interrupt()
,将线程的中断状态设置为true
。
Note: When the interrupt method is called on a thread that blocks on a call such as sleep or wait, the blocking call is terminated by an
InterruptedException
, which should be handled:
try {
while (!Thread.currentThread().isInterrupted() && /* more work to do */) {
// do more work
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// thread was interrupted during sleep or wait
}
关于java - 这是我应该在 Java 中停止线程的方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35641663/