说明
CompletableFuture是java8 中用来并发编程使用的,非常方便,功能上可以替换Semaphore的使用
1 import java.util.Random; 2 import java.util.concurrent.*; 3 4 5 public class FutureTest { 6 7 // 线程池 8 private static ExecutorService executorService = Executors.newFixedThreadPool(3); 9 10 public static void main(String[] args) { 11 try { 12 StringBuilder sb = new StringBuilder(); 13 14 // 正常操作 15 CompletableFuture<String> c1 = CompletableFuture.supplyAsync(() -> { 16 sleep(); 17 return "1"; 18 }, executorService).thenApply(s -> { 19 sb.append(s); 20 return s; 21 }); 22 23 24 // 异常处理 25 CompletableFuture<String> c2 = CompletableFuture.supplyAsync(() -> { 26 sleep(); 27 throw new RuntimeException("exception"); 28 }, executorService).exceptionally(exception -> "exception_2").thenApply(obj -> { 29 sb.append(obj); 30 return obj.toString(); 31 }); 32 33 // 未报异常 34 CompletableFuture<String> c3 = CompletableFuture.supplyAsync(() -> { 35 sleep(); 36 return "3"; 37 }, executorService).exceptionally(s -> "exception").thenApply(obj -> { 38 sb.append(obj); 39 return obj; 40 }); 41 42 43 long start = System.currentTimeMillis(); 44 System.out.println("start:" + start); 45 CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(c1, c2, c3); 46 try { 47 //所有线程只等待1s,会有超时的,所以会报timeoutException,catch 住之后,会有上部分数据没有被处理(sb.append(xxx)) 48 voidCompletableFuture.get(1, TimeUnit.SECONDS); 49 } catch (Exception e) { 50 e.printStackTrace(); 51 } 52 53 54 long complete = System.currentTimeMillis(); 55 System.out.println("complete:" + complete); 56 System.out.println("cost:" + (complete - start)); 57 // 如果 调用 get方法,则会等待返回值,那么所有的sb.append 都会被处理 58 // System.out.println(c1.get()); 59 // System.out.println(c2.get()); 60 // System.out.println(c3.get()); 61 System.out.println(sb); 62 long finish = System.currentTimeMillis(); 63 System.out.println("finish:" + finish); 64 System.out.println("cost:" + (finish - start)); 65 66 } finally { 67 executorService.shutdown(); 68 } 69 70 } 71 72 private static void sleep() { 73 try { 74 Thread.sleep(new Random().nextInt(2000)); 75 } catch (InterruptedException e) { 76 e.printStackTrace(); 77 } 78 } 79 }