java異步編程歷史概述

1.Java5.0之前主要是通過Thread類,Runnable接口實現,主要的缺點是無法拿到異步線程的返回值,以及異常處理

new Thread(()-> System.out.println("111111"),"java5").start();

2.java5.0增加Future,Callable。主要缺點阻塞式編程,無法進行多個異步線程之間的操作,無法異常處理

ExecutorService executorService = Executors.newSingleThreadExecutor();
Callable<String> threadTask  = ()->"java7 callable";
Future<String> submit = executorService.submit(threadTask);
System.out.printf("java7 thread ===>%s \n",submit.get());
executorService.shutdown();

3.Java7.0引入Fork/join,類似於線程池,主要是壓榨本地cp。。個人感覺實際工作中應用的不多

4.引入CompletableFuture

樣例一:

CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()->{
            System.out.println("java8 thread....");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "8888....";
        });

        System.out.println(completableFuture.get());

 

樣例二:

List<Map<String, String>> result = new ArrayList<>();
        List<CompletableFuture<Boolean>> collect = Stream.of(1, 2, 3, 4, 10)
                .map(num ->
                        CompletableFuture.supplyAsync(() -> {
                            Map<String, String> hashMap = new HashMap<String, String>();
                            hashMap.put("i" + num, num + "");
                            try {
                                Thread.sleep(RandomUtils.nextInt(5000));
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            return hashMap;
                        }).thenApply(r -> result.add(r))).collect(Collectors.toList());

        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(collect.toArray(new CompletableFuture[]{}));
        voidCompletableFuture.join();

        System.out.println("===========main thread==========");
        for(Map<String,String> res:result){
            System.out.println(res.toString());
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章