首頁  >  文章  >  Java  >  Java如何使用future及時取得多執行緒運行結果的實例分析

Java如何使用future及時取得多執行緒運行結果的實例分析

黄舟
黄舟原創
2017-10-12 10:20:512724瀏覽

在Java程式設計中,有時候會需要及時取得執行緒的運作結果,本文就透過一個相關實例向大家介紹Java利用future及時取得執行緒運行結果的方法,需要的朋友可以參考。

Future介面是Java標準API的一部分,在java.util.concurrent套件中。 Future介面是Java執行緒Future模式的實現,可以來進行非同步運算。

有了Future就可以進行三段式的程式設計了,1.啟動多執行緒任務2.處理其他事3.收集多執行緒任務結果。從而實現了非阻塞的任務呼叫。在途中遇到一個問題,那就是雖然能非同步取得結果,但是Future的結果需要透過isdone來判斷是否有結果,或是使用get()函數來阻塞式取得執行結果。這樣就不能即時追蹤其他執行緒的結果狀態了,所以直接使用get還是要慎用,最好配合isdone來使用。

這裡有一個更好的方式來實現對任意一個執行緒運行完成後的結果都能及時取得的方法:使用CompletionService,它內部新增了阻塞佇列,從而取得future中的值,然後根據返回值做對應的處理。一般future使用和CompletionService使用的兩個測試案例如下:


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
 * 多线程执行,异步获取结果
 * 
 * @author i-clarechen
 *
 */
public class AsyncThread {
  public static void main(String[] args) {
    AsyncThread t = new AsyncThread();
    List<Future<String>> futureList = new ArrayList<Future<String>>();
    t.generate(3, futureList);
    t.doOtherThings();
    t.getResult(futureList);
  }
  /**
   * 生成指定数量的线程,都放入future数组
   * 
   * @param threadNum
   * @param fList
   */
  public void generate(int threadNum, List<Future<String>> fList) {
    ExecutorService service = Executors.newFixedThreadPool(threadNum);
    for (int i = 0; i < threadNum; i++) {
      Future<String> f = service.submit(getJob(i));
      fList.add(f);
    }
    service.shutdown();
  }
  /**
   * other things
   */
  public void doOtherThings() {
    try {
      for (int i = 0; i < 3; i++) {
        System.out.println("do thing no:" + i);
        Thread.sleep(1000 * (new Random().nextInt(10)));
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
  /**
   * 从future中获取线程结果,打印结果
   * 
   * @param fList
   */
  public void getResult(List<Future<String>> fList) {
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(getCollectJob(fList));
    service.shutdown();
  }
  /**
   * 生成指定序号的线程对象
   * 
   * @param i
   * @return
   */
  public Callable<String> getJob(final int i) {
    final int time = new Random().nextInt(10);
    return new Callable<String>() {
      @Override
      public String call() throws Exception {
        Thread.sleep(1000 * time);
        return "thread-" + i;
      }
    };
  }
  /**
   * 生成结果收集线程对象
   * 
   * @param fList
   * @return
   */
  public Runnable getCollectJob(final List<Future<String>> fList) {
    return new Runnable() {
      public void run() {
        for (Future<String> future : fList) {
          try {
            while (true) {
              if (future.isDone() && !future.isCancelled()) {
                System.out.println("Future:" + future
                    + ",Result:" + future.get());
                break;
              } else {
                Thread.sleep(1000);
              }
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    };
  }
}

運行結果列印和future放入列表時的順序一致,為0,1, 2:


do thing no:0
do thing no:1
do thing no:2
Future:java.util.concurrent.FutureTask@68e1ca74,Result:thread-0
Future:java.util.concurrent.FutureTask@3fb2bb77,Result:thread-1
Future:java.util.concurrent.FutureTask@6f31a24c,Result:thread-2

以下是先執行完的執行緒先處理的方案:


##

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
public class testCallable {
  public static void main(String[] args) {
    try {
      completionServiceCount();
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
  }
  /**
   * 使用completionService收集callable结果
   * @throws ExecutionException 
   * @throws InterruptedException 
   */
  public static void completionServiceCount() throws InterruptedException, ExecutionException {
    ExecutorService executorService = Executors.newCachedThreadPool();
    CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(
        executorService);
    int threadNum = 5;
    for (int i = 0; i < threadNum; i++) {
      completionService.submit(getTask(i));
    }
    int sum = 0;
    int temp = 0;
    for(int i=0;i<threadNum;i++){
      temp = completionService.take().get();
      sum += temp;
      System.out.print(temp + "\t");
    }
    System.out.println("CompletionService all is : " + sum);
    executorService.shutdown();
  }
  public static Callable<Integer> getTask(final int no) {
    final Random rand = new Random();
    Callable<Integer> task = new Callable<Integer>() {
      @Override
      public Integer call() throws Exception {
        int time = rand.nextInt(100)*100;
        System.out.println("thead:"+no+" time is:"+time);
        Thread.sleep(time);
        return no;
      }
    };
    return task;
  }
}

執行結果為最先結束的執行緒結果先被處理:



thead:0 time is:4200
thead:1 time is:6900
thead:2 time is:2900
thead:3 time is:9000
thead:4 time is:7100
  0  1  4  3  CompletionService all is : 10

總結

#######rrreee######總結######

以上是Java如何使用future及時取得多執行緒運行結果的實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn