teg*_*lus 7 java java.util.concurrent
我有一个漂亮而紧凑的代码,它不能像我预期的那样工作.
public class Test {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
for (;;) {
}
} finally {
System.out.println("FINALLY");
}
}
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> future = executor.submit(r);
try {
future.get(3, TimeUnit.SECONDS);
} catch (TimeoutException e) {
boolean c = future.cancel(true);
System.out.println("Timeout " + c);
} catch (InterruptedException | ExecutionException e) {
System.out.println("interrupted");
}
System.out.println("END");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
超时是真的
结束
问题:为什么不终止future.cancel(true)方法调用Runnable?程序将"END"写入输出后,"r"Runnable仍在运行.
问题是你的Runnable是不可中断的:任务中断是Java中的协作过程,如果被取消的代码被取消,它需要定期检查,否则它将不会响应中断.
您可以按如下方式修改代码,它应该按预期工作:
Runnable r = new Runnable() {
@Override public void run() {
try {
while (!Thread.currentThread.isInterrupted()) {}
} finally {
System.out.println("FINALLY");
}
}
};
Run Code Online (Sandbox Code Playgroud)