El programa siguiente muestra el problema (la última JVM & otras cosas):Thread.isInterrupted no funciona, Thread.interrupted hace
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();
}
No * siempre * no se detiene. – Jerome
En mi máquina lo hace. – ripper234
jerome, verifique la configuración del compilador ... tal vez esté usando una JVM anterior. – PaulP1975