Java中使用有返回值的线程
生活随笔
收集整理的這篇文章主要介紹了
Java中使用有返回值的线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在創建多線程程序的時候,我們常實現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.總結:
總結
以上是生活随笔為你收集整理的Java中使用有返回值的线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 重磅嘉宾公布,第四范式AI新品发布会进入
- 下一篇: 课程直播|极致AI助力新经济时代个性化精