Can you think about any reason why this code doesn't work and always outputs "finished", but the second example works without any problems. I'm using 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 return and updated sleep times and another example.