日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java中使用有返回值的线程

發(fā)布時間:2025/3/12 java 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java中使用有返回值的线程 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

在創(chuàng)建多線程程序的時候,我們常實現(xiàn)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;// 線程池(根據(jù)機器的核心數(shù))private final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());private void testCallable() throws InterruptedException {Future<String> future = null;try {/*** 在創(chuàng)建多線程程序的時候,我們常實現(xiàn)Runnable接口,Runnable沒有返回值,要想獲得返回值,Java5提供了一個新的接口Callable** Callable需要實現(xiàn)的是call()方法,而不是run()方法,返回值的類型有Callable的類型參數(shù)指定,* Callable只能由ExecutorService.submit() 執(zhí)行,正常結束后將返回一個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是否完成,完成后可以調(diào)用get()方法獲得future的值,* 如果直接調(diào)用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 接口,實現(xiàn)call 方法;
  • 獲得future對象之前可以使用isDone()方法檢測future是否完成,完成后可以調(diào)用get()方法獲得future的值,如果直接調(diào)用get()方法,get()方法將阻塞到線程結束。
  • 總結

    以上是生活随笔為你收集整理的Java中使用有返回值的线程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。