Can you think of any reason why this code does not work and always displays "finished", but the second example works without problems. I am using the latest JDK (8u45).
public static class MyClass implements Runnable {
@Override
public void run () {
try {
Thread.sleep (2000);
} catch (InterruptedException ex) {
System.out.println ("Interrupted");
return
}
System.out.println ("Finished");
}
public static void main (String [] args) {
// spot the difference ->
ExecutorService executorService = Executors.newWorkStealingPool (4);
Future future = executorService.submit (new MyClass ());
Thread.sleep (100);
future.cancel (true);
}
}
And the following example works flawlessly:
public static class MyClass implements Runnable {
@Override
public void run () {
try {
Thread.sleep (2000);
} catch (InterruptedException ex) {
System.out.println ("Interrupted");
return
}
System.out.println ("Finished");
}
public static void main (String [] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor ();
Future future = executorService.submit (new MyClass ());
Thread.sleep (100);
future.cancel (true);
}
}
EDIT: Added reverse and updated sleep times and another example.
JiriS