|
| 1 | +package com.winterbe.java8.samples.concurrent; |
| 2 | + |
| 3 | +import java.util.concurrent.ExecutionException; |
| 4 | +import java.util.concurrent.ExecutorService; |
| 5 | +import java.util.concurrent.Executors; |
| 6 | +import java.util.concurrent.Future; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | +import java.util.concurrent.TimeoutException; |
| 9 | + |
| 10 | +/** |
| 11 | + * @author Benjamin Winterberg |
| 12 | + */ |
| 13 | +public class Executors2 { |
| 14 | + |
| 15 | + public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { |
| 16 | +// test1(); |
| 17 | +// test2(); |
| 18 | + test3(); |
| 19 | + } |
| 20 | + |
| 21 | + private static void test3() throws InterruptedException, ExecutionException, TimeoutException { |
| 22 | + ExecutorService executor = Executors.newSingleThreadExecutor(); |
| 23 | + |
| 24 | + Future<Integer> future = executor.submit(() -> { |
| 25 | + try { |
| 26 | + TimeUnit.SECONDS.sleep(2); |
| 27 | + return 123; |
| 28 | + } |
| 29 | + catch (InterruptedException e) { |
| 30 | + throw new IllegalStateException("task interrupted", e); |
| 31 | + } |
| 32 | + }); |
| 33 | + |
| 34 | + future.get(1, TimeUnit.SECONDS); |
| 35 | + } |
| 36 | + |
| 37 | + private static void test2() throws InterruptedException, ExecutionException { |
| 38 | + ExecutorService executor = Executors.newSingleThreadExecutor(); |
| 39 | + |
| 40 | + Future<Integer> future = executor.submit(() -> { |
| 41 | + try { |
| 42 | + TimeUnit.SECONDS.sleep(1); |
| 43 | + return 123; |
| 44 | + } |
| 45 | + catch (InterruptedException e) { |
| 46 | + throw new IllegalStateException("task interrupted", e); |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + executor.shutdownNow(); |
| 51 | + future.get(); |
| 52 | + } |
| 53 | + |
| 54 | + private static void test1() throws InterruptedException, ExecutionException { |
| 55 | + ExecutorService executor = Executors.newSingleThreadExecutor(); |
| 56 | + |
| 57 | + Future<Integer> future = executor.submit(() -> { |
| 58 | + try { |
| 59 | + TimeUnit.SECONDS.sleep(1); |
| 60 | + return 123; |
| 61 | + } |
| 62 | + catch (InterruptedException e) { |
| 63 | + throw new IllegalStateException("task interrupted", e); |
| 64 | + } |
| 65 | + }); |
| 66 | + |
| 67 | + System.out.println("future done: " + future.isDone()); |
| 68 | + |
| 69 | + Integer result = future.get(); |
| 70 | + |
| 71 | + System.out.println("future done: " + future.isDone()); |
| 72 | + System.out.print("result: " + result); |
| 73 | + |
| 74 | + executor.shutdownNow(); |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments