【发布时间】:2017-09-05 17:01:36
【问题描述】:
我现在正试图为一个已经在 groovy 中工作了几个小时的线程获得一个简单的中断。
不知何故,以下代码不会在线程“名称”中设置“中断”标志。导致循环运行直到结束。
发现了很多其他问题,通常缺少Thread.currentThread().isInterrupted() 的检查。但这里不是这样:
def t = Thread.start('name') {
try {
for (int i = 0; i < 10 && !Thread.currentThread().isInterrupted(); ++i) {
println "$i"
sleep 1000
}
} catch (InterruptedException e) {
println "Catched exception"
Thread.currentThread().interrupt();
}
}
println "Interrupting thread in 1..."
sleep 1000
println "Interrupting thread..."
t.interrupt()
sleep 2000
我得到以下输出
Interrupting thread in 1...
0
Interrupting thread...
1
2
3
4
5
6
7
8
9
想知道我在这里想念什么/做错了吗?
还尝试使用 ExecutorService 并在返回的 Future 上调用 cancel(true)。也没用。
【问题讨论】:
标签: multithreading groovy interrupted-exception