Java Future例項 以非同步的方式讓勇者給魔王宮殿放個炸彈
阿新 • • 發佈:2018-12-13
一個java用future的例項...
詳細的不說了..看看程式碼吧
public static void main(String[] args) throws InterruptedException, ExecutionException { System.out.println("====勇者悄悄進入了宮殿"); //通過執行緒池管理多執行緒 ExecutorService threadPool = Executors.newCachedThreadPool(); //執行緒池提交一個非同步任務 System.out.println("====勇者安放了一個炸彈,並設定10分鐘後爆炸"); Future<HashMap<String,String>> future = threadPool.submit(new Callable<HashMap<String,String>>() { public HashMap<String,String> call() throws Exception { System.out.println("炸彈開始倒計時...."); Thread.sleep(10000); System.out.println("炸彈啟動...滴滴滴滴滴!!!!"); return new HashMap<String,String>(){ {this.put("futureKey", "Boom~炸彈爆炸了");} }; } }); System.out.println("====勇者放完炸彈後騎著自己的小馬飛快的回到了家"); boolean flag = true; while(flag){ Thread.sleep(1000); if(future.isDone() && !future.isCancelled()){ HashMap<String,String> futureResult = future.get(); System.out.println("====遠方傳來了好訊息,結果是:"+futureResult.get("futureKey")); flag = false; }else{ System.out.println("====勇者還在家靜靜的喝茶,等待著好訊息的到來"); } } //關閉執行緒池 if(!threadPool.isShutdown()){ threadPool.shutdown(); } }