Ágo*_*áth 18 java multithreading
我有以下代码:
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.
Run Code Online (Sandbox Code Playgroud)
renderThread.interrupt()不会中断线程,它会继续运行.如果我更换renderThread.interrupt()用.stop(),那么线程停止.但是,.stop()已弃用.那么,什么是停止线程的正确方法,如果stop被弃用并且interrupt不起作用?
cha*_*255 21
当你调用interrupt()时,它会触发一个布尔标志,告诉它应该停止的运行函数.这就是我经常写这样的运行函数的原因.
void run()
{
while(!Thread.interrupted())
{
//Do something
}
}
Run Code Online (Sandbox Code Playgroud)
仅仅因为你调用中断并不意味着线程会立即停止或根本不停止.这取决于运行功能中的内容.
要真正说明为什么你不应该使用Thread.stop()?
Doug Lea最近提到Thread.stop将是Java第一个实现Java的方法.
他对某人的评论作出回应:
此外,另一个同步的事情是它处理线程的异步中止(即thread.stop()).我知道stop()已被弃用,但你永远都不知道.
是:
但你知道!从JDK8开始,Thread.stop真的不见了.这是第一个被弃用的方法.它现在只抛出UnsupportedOperationException.
http://cs.oswego.edu/pipermail/concurrency-interest/2013-December/012028.html
你应该看看这篇文章:http: /10kloc.wordpress.com/2013/03/03/java-multithreading-steeplechase-stopping-threads/
基本上你不应该停止线程(不安全),但要中断它.你缺少的是让线程处理中断.
| 归档时间: |
|
| 查看次数: |
44317 次 |
| 最近记录: |