標籤:pool 檢測 sub lse stack The exec == 阻塞
在建立多線程程式的時候,我們常實現Runnable介面,Runnable沒有傳回值,要想獲得傳回值,Java5提供了一個新的介面Callable,可以擷取線程中的傳回值,但是擷取線程的傳回值的時候,需要注意,我們的方法是非同步,擷取傳回值的時候,線程任務不一定有傳回值,所以,需要判斷線程是否結束,才能夠去取值。
測試代碼
package com.wuwii.test;import java.util.concurrent.*;/** * @author Zhang Kai * @version 1.0 * @since <pre>2017/10/31 11:17</pre> */public class Test { private static final Integer SLEEP_MILLS = 3000; private static final Integer RUN_SLEEP_MILLS = 1000; private int afterSeconds = SLEEP_MILLS / RUN_SLEEP_MILLS; // 線程池(根據機器的核心數) private final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); private void testCallable() throws InterruptedException { Future<String> future = null; try { /** * 在建立多線程程式的時候,我們常實現Runnable介面,Runnable沒有傳回值,要想獲得傳回值,Java5提供了一個新的介面Callable * * Callable需要實現的是call()方法,而不是run()方法,傳回值的類型有Callable的型別參數指定, * Callable只能由ExecutorService.submit() 執行,正常結束後將返回一個future對象。 */ future = fixedThreadPool.submit(() -> { Thread.sleep(SLEEP_MILLS); return "The thread returns value."; }); } catch (Exception e) { e.printStackTrace(); } if (future == null) return; for (;;) { /** * 獲得future對象之前可以使用isDone()方法檢測future是否完成,完成後可以調用get()方法獲得future的值, * 如果直接調用get()方法,get()方法將阻塞到線程結束,很浪費。 */ if (future.isDone()) { try { System.out.println(future.get()); break; } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } else { System.out.println("After " + afterSeconds-- + " seconds,get the future returns value."); Thread.sleep(1000); } } } public static void main(String[] args) throws InterruptedException { new Test().testCallable(); }}
運行結果:
After 3 seconds,get the future returns value.After 2 seconds,get the future returns value.After 1 seconds,get the future returns value.The thread returns value.
總結:
- 需要傳回值的線程使用Callable 介面,實現call 方法;
- 獲得future對象之前可以使用isDone()方法檢測future是否完成,完成後可以調用get()方法獲得future的值,如果直接調用get()方法,get()方法將阻塞到線程結束。
Java中使用有傳回值的線程