Future模式

    创建1~n个线程执行别的异步任务,并可要求这些线程返回异步任务的执行结果。

    code

    1. package concurrent;
    2. import java.util.concurrent.*;
    3. public class C12_FuturePattern {
    4. static class RealData implements Callable<String>{
    5. private String data;
    6. public RealData(String data){ this.data = data; }
    7. @Override
    8. public String call() throws Exception {
    9. Thread.sleep(2000); //模拟任务
    10. return data.toUpperCase();
    11. }
    12. }
    13. public static void main(String[] args) throws ExecutionException, InterruptedException {
    14. //1.创建线程池
    15. ExecutorService es = Executors.newFixedThreadPool(1);
    16. //2.提交一个实现了Callable接口的任务并立即返回
    17. Future<String> future = es.submit(new RealData("abcdefg"));
    18. System.out.println("task was submit.");
    19. //3.主线程做其他事情
    20. doOtherWork();
    21. //4.主线程通过future获取所提交任务返回的数据,若还没完成那么会在get函数出阻塞
    22. System.out.println(future.get());
    23. es.shutdown();
    24. }
    25. public static void doOtherWork(){
    26. System.out.println("other work was completed, wait for future.get().");
    27. }
    28. }

    console

    1. task was submit.
    2. other work was completed, wait for future.get().
    3. ABCDEFG