線(xiàn)程池 ExecutorService 相信java開(kāi)發(fā)都用到,這里做個(gè)簡(jiǎn)單筆記
一 Java通過(guò)Executors提供四種線(xiàn)程池,分別為:
newCachedThreadPool創(chuàng )建一個(gè)可緩存線(xiàn)程池,如果線(xiàn)程池長(cháng)度超過(guò)處理需要,可靈活回收空閑線(xiàn)程,若無(wú)可回收,則新建線(xiàn)程。
newFixedThreadPool 創(chuàng )建一個(gè)定長(cháng)線(xiàn)程池,可控制線(xiàn)程最大并發(fā)數,超出的線(xiàn)程會(huì )在隊列中等待。
newScheduledThreadPool 創(chuàng )建一個(gè)定長(cháng)線(xiàn)程池,支持定時(shí)及周期性任務(wù)執行。
newSingleThreadExecutor 創(chuàng )建一個(gè)單線(xiàn)程化的線(xiàn)程池,它只會(huì )用唯一的工作線(xiàn)程來(lái)執行任務(wù),保證所有任務(wù)按照指定順序(FIFO, LIFO, 優(yōu)先級)執行。
二、 ExecutorService 的submit() 與execute()區別
1、接收的參數不一樣 submit()可以接受runnable無(wú)返回值和callable有返回值
execute()接受runnable 無(wú)返回值
2、submit有返回值,而execute沒(méi)有
Method submit extends base method Executor.execute by creating and returning a Future that can be used to cancel execution and/or wait for completion.
用到返回值的例子,比如說(shuō)我有很多個(gè)做validation的task,我希望所有的task執行完,然后每個(gè)task告訴我它的執行結果,是成功還是失敗,如果是失敗,原因是什么。
3、submit方便Exception處理
There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked or not, is then part of the task’s return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will rethrow this exception, wrapped in an ExecutionException.
意思就是如果你在你的task里會(huì )拋出checked或者unchecked exception,而你又希望外面的調用者能夠感知這些exception并做出及時(shí)的處理,那么就需要用到submit,通過(guò)捕獲Future.get拋出的異常。
import java.util.ArrayList; import java.util.List; import java.util.Random; 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; public class ExecutorServiceTest { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); List<Future<String>> resultList = new ArrayList<Future<String>>(); // 創(chuàng )建10個(gè)任務(wù)并執行 for (int i = 0; i < 10; i++) { // 使用ExecutorService執行Callable類(lèi)型的任務(wù),并將結果保存在future變量中 Future<String> future = executorService.submit(new TaskWithResult(i)); // 將任務(wù)執行結果存儲到List中 resultList.add(future); } executorService.shutdown(); // 遍歷任務(wù)的結果 for (Future<String> fs : resultList) { try { System.out.println(fs.get()); // 打印各個(gè)線(xiàn)程(任務(wù))執行的結果 } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { executorService.shutdownNow(); e.printStackTrace(); return; } } } } class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } /** * 任務(wù)的具體過(guò)程,一旦任務(wù)傳給ExecutorService的submit方法,則該方法自動(dòng)在一個(gè)線(xiàn)程上執行。 * * @return * @throws Exception */ public String call() throws Exception { System.out.println("call()方法被自動(dòng)調用,干活?。?! " + Thread.currentThread().getName()); if (new Random().nextBoolean()) throw new TaskException("Meet error in task." + Thread.currentThread().getName()); // 一個(gè)模擬耗時(shí)的操作 for (int i = 999999999; i > 0; i--) ; return "call()方法被自動(dòng)調用,任務(wù)的結果是:" + id + " " + Thread.currentThread().getName(); } } class TaskException extends Exception { public TaskException(String message) { super(message); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
執行的結果類(lèi)似于:
call()方法被自動(dòng)調用,干活?。?! pool-1-thread-1 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-2 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-3 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-5 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-7 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-4 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-6 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-7 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-5 call()方法被自動(dòng)調用,干活?。?! pool-1-thread-8 call()方法被自動(dòng)調用,任務(wù)的結果是:0 pool-1-thread-1 call()方法被自動(dòng)調用,任務(wù)的結果是:1 pool-1-thread-2 java.util.concurrent.ExecutionException: com.cicc.pts.TaskException: Meet error in task.pool-1-thread-3 at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222) at java.util.concurrent.FutureTask.get(FutureTask.java:83) at com.cicc.pts.ExecutorServiceTest.main(ExecutorServiceTest.java:29) Caused by: com.cicc.pts.TaskException: Meet error in task.pool-1-thread-3 at com.cicc.pts.TaskWithResult.call(ExecutorServiceTest.java:57) at com.cicc.pts.TaskWithResult.call(ExecutorServiceTest.java:1) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
可以看見(jiàn)一旦某個(gè)task出錯,其它的task就停止執行。
三、shotdown() showdownNow()區別
可以關(guān)閉 ExecutorService,這將導致其拒絕新任務(wù)。提供兩個(gè)方法來(lái)關(guān)閉 ExecutorService。
shutdown() 方法在終止前允許執行以前提交的任務(wù),
shutdownNow() 方法阻止等待任務(wù)啟動(dòng)并試圖停止當前正在執行的任務(wù)。在終止時(shí)執行程序沒(méi)有任務(wù)在執行,也沒(méi)有任務(wù)在等待執行,并且無(wú)法提交新任務(wù)。關(guān)閉未使用的 ExecutorService 以允許回收其資源。
一般分兩個(gè)階段關(guān)閉 ExecutorService。第一階段調用 shutdown 拒絕傳入任務(wù),然后調用 shutdownNow(如有必要)取消所有遺留的任務(wù)
// 啟動(dòng)一次順序關(guān)閉,執行以前提交的任務(wù),但不接受新任務(wù)。 threadPool.shutdown();
四、Runnable()與Callable()區別
如果是一個(gè)多線(xiàn)程協(xié)作程序,比如菲波拉切數列,1,1,2,3,5,8…使用多線(xiàn)程來(lái)計算。
但后者需要前者的結果,就需要用callable接口了。
callable用法和runnable一樣,只不過(guò)調用的是call方法,該方法有一個(gè)泛型返回值類(lèi)型,你可以任意指定。
runnable接口實(shí)現的沒(méi)有返回值的并發(fā)編程。
callable實(shí)現的存在返回值的并發(fā)編程。(call的返回值String受泛型的影響) 使用Future獲取返回值。