1. 程式人生 > >非同步返回結果測試demo

非同步返回結果測試demo


import java.util.HashMap;
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;

/** 
 * @date 建立時間:2017年2月7日 上午11:33:11 
 * @Description: 
 */
public class FutureTest {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        //通過執行緒池管理多執行緒
        ExecutorService threadPool = Executors.newFixedThreadPool(2);

        //執行緒池提交一個非同步任務
        System.out.println("====提交非同步任務");
        Future<HashMap<String,String>> future = threadPool.submit(new Callable<HashMap<String,String>>() {

            @Override
            public HashMap<String,String> call() throws Exception {

                System.out.println("非同步任務開始執行....");
                Thread.sleep(10000);
                System.out.println("非同步任務執行完畢,返回執行結果!!!!");

                return new HashMap<String,String>(){
                    {this.put("futureKey", "成功獲取future非同步任務結果");}
                };
            }

        });

        System.out.println("====提交非同步任務之後,立馬返回到主執行緒繼續往下執行");
        Thread.sleep(1000);


        boolean flag = true;
        while(flag){
            //非同步任務完成並且未被取消,則獲取返回的結果
            if(future.isDone() && !future.isCancelled()){
                HashMap<String,String> futureResult = future.get();
                System.out.println("====非同步任務返回的結果是:"+futureResult.get("futureKey"));
                flag = false;
            }
        }

        //關閉執行緒池
        if(!threadPool.isShutdown()){
            threadPool.shutdown();
        }
    }
}