三.多執行緒JUC篇-3.19 CompletionService

weixin_42868638發表於2020-12-30

1.future的缺陷

package com.dwz.executors;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
 * future的缺陷
 * 1.No callback 不能回撥
 * 2.不能拿到最先執行完成的結果,浪費時間資源
 */
public class CompletionServiceExample1 {
    
    /**
     * No callback 不能回撥
     * @throws InterruptedException
     * @throws ExecutionException
     */
    private static void futureDefect1() throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<Integer> future = service.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 100;
        });
        System.out.println("==============");
        //一旦要取得返回值會產生阻塞
        future.get();
    }
    
    //不能拿到最先執行完成的結果,浪費時間資源
    private static void futureDefect2() throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        final List<Callable<Integer>> callableList = Arrays.asList(
                () -> {
                    sleep(10);
                    System.out.println("The 10 finished.");
                    return 10;
                },
                () -> {
                    sleep(20);
                    System.out.println("The 20 finished.");
                    return 20;
                }
        );
        
        List<Future<Integer>> futures = new ArrayList<>();
        futures.add(service.submit(callableList.get(0)));
        futures.add(service.submit(callableList.get(1)));
        
        for(Future<Integer> future : futures) {
            System.out.println(future.get());
        }
        
//        List<Future<Integer>> futures = service.invokeAll(callableList);
//        Integer v1 = futures.get(1).get();
//        System.out.println(v1);
//        Integer v2 = futures.get(0).get();
//        System.out.println(v2);
    }
    
    private static void sleep(long seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        futureDefect1();
        futureDefect2();
    }
}

2.CompletionService對Future的優化

package com.dwz.executors;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
 *    比如有兩個執行緒同時執行,其中一個很快執行完,另一個耗時太長我不想等待,想先拿到第一個執行緒的處理結果進行業務處理
 */
public class CompletionServiceExample2 {
    
    private static void sleep(long seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    //解決了可以優先獲取先執行完的結果
    private static void testCompletionServiceSubmitCallable() throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        final List<Callable<Integer>> callableList = Arrays.asList(
                () -> {
                    sleep(10);
                    System.out.println("The 10 finished.");
                    return 10;
                },
                () -> {
                    sleep(5);
                    System.out.println("The 5 finished.");
                    return 5;
                }
        );
        
        ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<>(service);
        List<Future<Integer>> futures = new ArrayList<>();
        callableList.stream().forEach(callable -> futures.add(completionService.submit(callable)));
        
        Future<Integer> future;
        while((future = completionService.take()) != null) {
            System.out.println(future.get());
        }
        
//        Future<Integer> future = completionService.poll();
//        System.out.println(future);
        
//        System.out.println(completionService.poll(11, TimeUnit.SECONDS).get());
    }
    
    private static void testCompletionServiceSubmitRunnable() throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(2);
        ExecutorCompletionService<Event> completionService = new ExecutorCompletionService<>(service);
        final Event event = new Event(1);
        //給runnable一個返回值Event result
        completionService.submit(new MyTask(event), event);
        System.out.println(completionService.take().get().result);
    }
    
    private static class Event {
        final private int eventId;
        private String result;
        
        public Event(int eventId) {
            this.eventId = eventId;
        }

        public int getEventId() {
            return eventId;
        }
        
        public void setResult(String result) {
            this.result = result;
        }

        public String getResult() {
            return result;
        }
    }
    
    private static class MyTask implements Runnable {
        private final Event event;
        
        private MyTask(Event event) {
            this.event = event;
        }
        
        @Override
        public void run() {
            sleep(10);
            event.setResult("I am successful.");
        }
        
    }
    
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        testCompletionServiceSubmitCallable();
        testCompletionServiceSubmitRunnable();
    }
}

相關文章