一、建立任務
任務可以理解為一段獨立執行的代碼,它完成一定的功能。
在Java 5及以上版本中不僅可以利用 Runnable介面,還可以利用Callable介面。
兩種任務的區別:Runnable 的run()方法完成的任務是沒有傳回值的 - void
而Callable 的call()方法完成的任務是有傳回值的 - 傳回值 有介面的泛型<V> 來制定
二、執行任務
通過java.util.concurrent.ExecutorService介面對象來執行任務,
這個介面對象由工具類java.util.concurrent.Executors的靜態方法來建立。
相關類及介面說明:
Executors 提供建立線程池或線程工廠的方法.
ExecutorService 提供了管理終止的方法,以及可為跟蹤一個或多個非同步任務執行狀況而產生 Future 的方法。
Executor 可以簡單理解為一個線程的執行者,是Executors 的上一級介面。
Callable 線程要執行而去實現的介面
Future 表示非同步計算的結果,對執行的線程的狀態檢查,可以獲得執行結果.
下面以一個例子來說明:
public class CallableDemo {</p><p>public static void main(String[] args) {</p><p>/**<br /> * Executors.newFixedThreadPool(5)建立一個線程池,<br /> * 這個線程池中維護 5 個線程的執行與銷毀工作,並將維護的工作交給 ExecutorService 去處理<br /> */<br />ExecutorService service = Executors.newFixedThreadPool(5);<br />// ExecutorService service = Executors.newCachedThreadPool();</p><p>/**<br /> * 記錄線程的 任務(這裡由實現了Callable介面 的類來執行)的返回介面<br /> */<br />List<Future<String>> resultList = new ArrayList<Future<String>>();</p><p>/**<br /> * 建立 10個任務<br /> */<br />for (int i = 0; i < 10; i++) {</p><p>/**<br /> * ExecutorService 的 submit方法 來維護任務(這個任務不是線程,是Callable,但是和線程的工作原理是一樣的)的運行狀態<br /> */<br />Future<String> future = service.submit(new TaskWithResult(i));<br /> //將任務的結果加入<br />resultList.add(future);</p><p>}<br /> //遍曆結果<br />for (Future<String> f : resultList) {</p><p>try {</p><p>System.out.println("Future result: " + f.get());</p><p>} catch (InterruptedException e) {</p><p>e.printStackTrace();</p><p>} catch (ExecutionException e) {</p><p>e.printStackTrace();</p><p>} finally {</p><p>service.shutdown();</p><p>}</p><p>}</p><p>}</p><p>}
class TaskWithResult implements Callable<String> {</p><p>private int id;</p><p>public TaskWithResult(int id) {</p><p>this.id = id;</p><p>}</p><p>/**<br /> * 這裡的傳回型別要與Callable制定的泛型型別要一致<br /> */<br />@Override<br />public String call() throws Exception {</p><p>int delay = (int) (Math.random() * 3000);</p><p>/**<br /> * 讓線程休眠一下,以便於結果查看<br /> */<br />System.out.println("Call executed ...."<br />+ Thread.currentThread().getName() + " - sleep: " + delay<br />+ " ms");</p><p>Thread.sleep(delay);</p><p>return "call feedback result " + this.id;</p><p>}</p><p>}
查看輸出:
Call executed ....pool-1-thread-2 - sleep: 1560 ms<br />Call executed ....pool-1-thread-3 - sleep: 467 ms<br />Call executed ....pool-1-thread-1 - sleep: 1619 ms<br />Call executed ....pool-1-thread-5 - sleep: 2817 ms<br />Call executed ....pool-1-thread-4 - sleep: 72 ms<br />Call executed ....pool-1-thread-4 - sleep: 711 ms<br />Call executed ....pool-1-thread-3 - sleep: 392 ms<br />Call executed ....pool-1-thread-4 - sleep: 2248 ms<br />Call executed ....pool-1-thread-3 - sleep: 2537 ms<br />Call executed ....pool-1-thread-2 - sleep: 646 ms<br />Future result: call feedback result 0<br />Future result: call feedback result 1<br />Future result: call feedback result 2<br />Future result: call feedback result 3<br />Future result: call feedback result 4<br />Future result: call feedback result 5<br />Future result: call feedback result 6<br />Future result: call feedback result 7<br />Future result: call feedback result 8<br />Future result: call feedback result 9
看線程的名字都是類似於“pool-1-thread-4” 的字串,可是為什麼最大的索引是5呢?
對了,這裡就與線程池中維護的線程數量有關了 當你改變線程池的大小時,這裡的資料時會跟著變的,
service.submit(Callable callable)是來運行 Callable類型的任務,也可運行Runnable類型的任務
而
service.execute(Runnable runnable)只能用來運行 Runnable類型的任務
註:這個execute方法是其父借口java.util.concurrent.Execute中的一個方法
大家也可以試試
ExecutorService service = Executors.newCachedThreadPool();
看輸出的名字Thread名字會有什麼變化