fork download
  1. import java.util.concurrent.CompletableFuture;
  2. import java.util.concurrent.ExecutionException;
  3.  
  4. class Demo {
  5.  
  6. public static void main(String[] args) throws InterruptedException, ExecutionException {
  7.  
  8. CompletableFuture<Integer> sharedFuture = new CompletableFuture<>();
  9.  
  10. Thread computing = new Thread(() -> {
  11. int value = 1;
  12. try {
  13. while (!Thread.currentThread().isInterrupted() &&
  14. !sharedFuture.isDone()) {
  15. value = value * 32 + 7;
  16. }
  17. } catch (Throwable t) {
  18. sharedFuture.completeExceptionally(t);
  19. } finally {
  20. // has no effect if already completed.
  21. sharedFuture.complete(value);
  22. }
  23. });
  24. computing.start();
  25.  
  26. try {
  27. Thread.sleep((long) (5000 * Math.random()));
  28. } catch (InterruptedException ignored) {
  29. }
  30.  
  31. computing.interrupt();
  32. System.out.println(sharedFuture.get());
  33. }
  34. }
  35.  
Success #stdin #stdout 4.47s 321152KB
stdin
Standard input is empty
stdout
-831283993