Java併發程式設計——執行緒池的使用(六)執行緒池的常用方法
阿新 • • 發佈:2019-02-14
整理了一下執行緒池經常用到的方法:
//是否正在shutdown()
executor.isTerminating();
//是否已經shutdown()
executor.isTerminated();
//在3秒內是否shutdown(),如果不呼叫shutdown(),線上程池中仍有任務時,會有堵塞效果(時間結束或任務結束釋放)
boolean b = executor.awaitTermination(3, TimeUnit.SECONDS);
//允許核心執行緒超時
executor.allowsCoreThreadTimeOut();
executor.allowCoreThreadTimeOut(true );
//增加一條核心執行緒,但不能超過核心執行緒最大值,返回是否成功
boolean b = executor.prestartCoreThread();
//啟動全部核心執行緒,返回核心執行緒的數量
int i = executor.prestartAllCoreThreads();
//獲取完成的任務數
executor.getCompletedTaskCount();
//重寫beforeExecute和afterExecute 任務執行前,任務執行完成
//移除未進行的任務是否成功 executor.submit()提交的任務不可移除
boolean remove = executor.remove(Runnable);
//獲取正在進行任務的執行緒數量
executor.getActiveCount();
關於執行Callable的方法:
List<Callable<String>> list = new ArrayList<>();
list.add(new MyCallable("123"));
list.add(new MyCallable("456"));
list.add(new MyCallable("789"));
//執行list裡的所有任務,並返回第一個執行完畢的結果
String s = executor.invokeAny(list);
//執行list裡的所有任務,並在3秒內返回第一個執行完畢的結果
String s = executor.invokeAny(list, 3, TimeUnit.SECONDS);
//按順序執行list裡的任務,阻塞程序,所有任務執行完畢並返回結果
List<Future<String>> s = executor.invokeAll(list);
//按順序執行list裡的任務,阻塞程序,3秒內所有任務執行完畢並返回結果,呼叫Future.get()方法不再阻塞
List<Future<String>> s = executor.invokeAll(list, 3, TimeUnit.SECONDS);
這裡寫的不是很詳細,因為我想另起一篇部落格寫下Future和Callable,連線:
還沒寫好,稍等。。。