下面的程序演示了此问题(最新JVM &诸如此类的东西):Thread.isInterrupted不起作用,Thread.interrupted确实
public static void main(String[] args) throws InterruptedException {
// if this is true, both interrupted and isInterrupted work
final boolean withPrint = false;
// decide whether to use isInterrupted or interrupted.
// if this is true, the program never terminates.
final boolean useIsInterrupted = true;
ExecutorService executor = Executors.newSingleThreadExecutor();
final CountDownLatch latch = new CountDownLatch(1);
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() throws Exception {
Random random = new Random();
while (true) {
if (withPrint) {
System.out.println(random.nextInt());
System.out.flush();
}
if (useIsInterrupted)
{
if (Thread.currentThread().isInterrupted())
break;
}
else
{
if (Thread.interrupted())
break;
}
}
System.out.println("Nice shutdown");
latch.countDown();
return null;
}
};
System.out.println("Task submitted");
Future<Void> task = executor.submit(callable);
Thread.sleep(100);
task.cancel(true);
latch.await();
System.out.println("Main exited");
executor.shutdown();
}
它不*总是*不能停止。 – Jerome 2010-01-06 10:57:25
在我的机器上它有。 – ripper234 2010-01-06 11:00:29
jerome,检查你的编译器设置...也许你正在使用更早的JVM。 – PaulP1975 2010-01-06 12:07:14