日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Callable 和 Future接口 学习

發布時間:2025/3/15 编程问答 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Callable 和 Future接口 学习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

* Callable是類似于Runnable的接口,實現Callable接口的類和實現Runnable的類都是可被其它線程執行的任務。

* Callable和Runnable有幾點不同:

* (1)Callable規定的方法是call(),而Runnable規定的方法是run().

* (2)Callable的任務執行后可返回值,而Runnable的任務是不能返回值的。

* (3)call()方法可拋出異常,而run()方法是不能拋出異常的。

* (4)運行Callable任務可拿到一個Future對象,

* Future 表示異步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,并檢索計算的結果。

* 通過Future對象可了解任務執行情況,可取消任務的執行,還可獲取任務執行的結果。

例子:

public class TimeOut { public static void main(String[] args){ int timeout = 2; //秒. ExecutorService executor = Executors.newSingleThreadExecutor(); Boolean result = false; Future<Boolean> future = executor.submit(new MyJob("請求參數=="));// 將任務提交到線程池中 try { result = future.get(timeout*10000, TimeUnit.MILLISECONDS);// 設定在200毫秒的時間內完成 System.out.println(result); } catch (InterruptedException e) { System.out.println("線程中斷出錯。"); future.cancel(true);// 中斷執行此任務的線程 } catch (ExecutionException e) { System.out.println("線程服務出錯。"); future.cancel(true);// 中斷執行此任務的線程 } catch (TimeoutException e) {// 超時異常 System.out.println("超時。"); future.cancel(true);// 中斷執行此任務的線程 }finally{ System.out.println("線程服務關閉。"); executor.shutdown(); } } static class MyJob implements Callable<Boolean> { private String t; public MyJob(String temp){ this.t= temp; } public Boolean call() { //調整i大小測試超時for(int i=0;i<999999999;i++){ if(i==2){ System.out.println(t); } if (Thread.interrupted()){ //很重要 return false; } } System.out.println("繼續執行.........."); return true; } } } public class TimeoutTest1 {public static void main(String[] args) {final ExecutorService service = Executors.newFixedThreadPool(1);TaskThread taskThread = new TaskThread();System.out.println("提交任務...begin");Future<Object> taskFuture = service.submit(taskThread);System.out.println("提交任務...end");try {Object re = taskFuture.get(6000, TimeUnit.MILLISECONDS);// 超時設置,6sSystem.out.println(re);} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} catch (TimeoutException e) {System.out.println("超時 取消任務");taskFuture.cancel(true);System.out.println("超時 取消任務OK");} finally {service.shutdown();}} }class TaskThread implements Callable<Object> {public Object call() throws Exception {String result = "空結果";try {System.out.println("任務開始....");//修改sleep 的值測試超時Thread.sleep(500);result = "正確結果";System.out.println("任務結束....");} catch (Exception e) {System.out.println("Task is interrupted!");}return result;} }

?

轉載于:https://www.cnblogs.com/sprinng/p/5849710.html

總結

以上是生活随笔為你收集整理的Callable 和 Future接口 学习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。