max*_*mus 12 java multithreading thread-safety threadpool
我试图在我的线程池中关闭所有线程.
通常我会尝试:
while(!Thread.currentThread().isInterrupted()) {...
Run Code Online (Sandbox Code Playgroud)
关闭while循环...
但我有一个仅包含的线程
while(!Thread.currentThread().isInterrupted()) {//which is true
Run Code Online (Sandbox Code Playgroud)
这是我关闭线程的方式:
pool.shutdownNow();
Run Code Online (Sandbox Code Playgroud)
那你怎么关闭这样一个线程呢?
Ami*_*nde 15
您可以添加volatile
布尔值flag
.
public class Worker implements Runnable {
volatile boolean cancel = false;
@Override
public void run() {
while (!cancel) {
// Do Something here
}
}
public void cancel() {
cancel = true;
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以打电话了
worker.cancel();
Run Code Online (Sandbox Code Playgroud)
更新:
从Java doc of shutdownNow()
尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表.
除了尽力尝试停止处理主动执行任务之外,这里不能保证.例如,典型的实现将通过Thread.interrupt()取消,因此任何未能响应中断的任务都可能永远不会终止.
因此,您必须通过保留中断来定义中断策略
catch (InterruptedException ie) {
// Preserve interrupt status
Thread.currentThread().interrupt();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5597 次 |
最近记录: |