fork download
  1. import java.util.concurrent.Callable;
  2. import java.util.concurrent.FutureTask;
  3. import java.util.concurrent.TimeUnit;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8. //GOAL: make "cancel(true)" interrupt the thread that calls get()
  9.  
  10. // a task that just blocks and sets the interrupted flag
  11. final FutureTask<Void> task = new FutureTask<>(new Callable<Void>() {
  12. @Override
  13. public Void call() throws Exception {
  14. try {
  15. Thread.sleep(Long.MAX_VALUE);
  16. } finally {
  17. // the interrupted flag must be set manually to carry through
  18. Thread.currentThread().interrupt();
  19. }
  20. return null;
  21. }
  22. });
  23.  
  24. // a different thread to cancel above task, since this thread will be
  25. // blocked by executing avove task.
  26. new Thread() {
  27. public void run() {
  28. try {
  29. Thread.sleep(1000);
  30. } catch (Exception e) {}
  31. task.cancel(true);
  32. }
  33. }.start();
  34.  
  35. // task executed in local thread
  36. task.run();
  37.  
  38. // both task & this thread should be interrupted now:
  39. System.out.println("This thread interrupted? " + Thread.currentThread().isInterrupted());
  40.  
  41. try {
  42. task.get(1, TimeUnit.MINUTES);
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. }
  48.  
Success #stdin #stdout #stderr 0.08s 380480KB
stdin
Standard input is empty
stdout
This thread interrupted? true
stderr
java.lang.InterruptedException
	at java.util.concurrent.locks.AbstractQueuedSynchronizer.tryAcquireSharedNanos(AbstractQueuedSynchronizer.java:1325)
	at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:257)
	at java.util.concurrent.FutureTask.get(FutureTask.java:119)
	at Main.main(Main.java:42)