gpt4 book ai didi

java - 这是我应该在 Java 中停止线程的方式吗?

转载 作者:行者123 更新时间:2023-11-30 06:10:39 25 4
gpt4 key购买 nike

我的老师告诉我不要使用 stop() 而是在 Thread 类中使用这种方式:

public void pararHilo() { 
stopHilo = true;
}

public void run() {
while (!stopHilo)
c++;
}

据我所知,当 pararHilo() 被调用时,循环结束,因此它退出 run() 方法并且 Thread 结束。问题是我有一台相当不错的笔记本电脑,当使用这段代码(在这里和在学校)进行测试时,我的机器变得非常迟钝,我不得不关闭 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com