我的老师告诉我不要在Thread类中使用stop(),而是使用这种方式:
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/