Java Thread.stop()vs Thread.interrupt() [英] Java Thread.stop() vs Thread.interrupt()
问题描述
我有以下代码:
renderThread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000000; i++) {
System.out.println("Number: " + i);
}
}
});
renderThread.start();
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
renderThread.interrupt(); //It should stop, but it does not stop.
renderThread.interrupt()
不会中断线程,它继续运行。如果我用 .stop()
替换 renderThread.interrupt()
,则线程停止。但是,不推荐使用 .stop()
。
然后,如果 stop
被弃用且中断
没有,那么停止线程的正确方法是什么工作?
renderThread.interrupt()
does not interrupt the thread, it continues to run. If I replace renderThread.interrupt()
with .stop()
, then the thread stops. However, .stop()
is deprecated.
Then, what is the proper way of stopping a thread, if stop
is deprecated and interrupt
does not work?
推荐答案
当你调用interrupt()时,它会触发一个布尔标志,告诉它应该停止的运行函数。这就是为什么我经常写这样的运行函数。
When you call interrupt() it triggers a boolean flag which tells the run function it should stop. That is why I usually write my run functions like this.
void run()
{
while(!Thread.interrupted())
{
//Do something
}
}
仅仅因为你打电话给中断并不意味着线程会立即停止或完全停止。这取决于运行函数中的内容。
Just because you call interrupt doesn't mean the thread will stop immediately or at all. It depends on what is in the run function.
这篇关于Java Thread.stop()vs Thread.interrupt()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!