激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專(zhuān)注于服務(wù)器技術(shù)及軟件下載分享
分類(lèi)導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語(yǔ)言|JavaScript|易語(yǔ)言|vb.net|

服務(wù)器之家 - 編程語(yǔ)言 - Java教程 - Java利用future及時(shí)獲取多線(xiàn)程運(yùn)行結(jié)果

Java利用future及時(shí)獲取多線(xiàn)程運(yùn)行結(jié)果

2021-01-16 11:28clare-chen Java教程

在Java編程中,有時(shí)候會(huì)需要及時(shí)獲取線(xiàn)程的運(yùn)行結(jié)果,本文就通過(guò)一個(gè)相關(guān)實(shí)例向大家介紹Java利用future及時(shí)獲取線(xiàn)程運(yùn)行結(jié)果的方法,需要的朋友可以參考。

Future接口是Java標(biāo)準(zhǔn)API的一部分,在java.util.concurrent包中。Future接口是Java線(xiàn)程Future模式的實(shí)現(xiàn),可以來(lái)進(jìn)行異步計(jì)算。

有了Future就可以進(jìn)行三段式的編程了,1.啟動(dòng)多線(xiàn)程任務(wù)2.處理其他事3.收集多線(xiàn)程任務(wù)結(jié)果。從而實(shí)現(xiàn)了非阻塞的任務(wù)調(diào)用。在途中遇到一個(gè)問(wèn)題,那就是雖然能異步獲取結(jié)果,但是Future的結(jié)果需要通過(guò)isdone來(lái)判斷是否有結(jié)果,或者使用get()函數(shù)來(lái)阻塞式獲取執(zhí)行結(jié)果。這樣就不能實(shí)時(shí)跟蹤其他線(xiàn)程的結(jié)果狀態(tài)了,所以直接使用get還是要慎用,最好配合isdone來(lái)使用。

這里有一種更好的方式來(lái)實(shí)現(xiàn)對(duì)任意一個(gè)線(xiàn)程運(yùn)行完成后的結(jié)果都能及時(shí)獲取的辦法:使用CompletionService,它內(nèi)部添加了阻塞隊(duì)列,從而獲取future中的值,然后根據(jù)返回值做對(duì)應(yīng)的處理。一般future使用和CompletionService使用的兩個(gè)測(cè)試案例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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;
/**
 * 多線(xiàn)程執(zhí)行,異步獲取結(jié)果
 *
 * @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);
  }
  /**
   * 生成指定數(shù)量的線(xiàn)程,都放入future數(shù)組
   *
   * @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中獲取線(xiàn)程結(jié)果,打印結(jié)果
   *
   * @param fList
   */
  public void getResult(List<Future<String>> fList) {
    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(getCollectJob(fList));
    service.shutdown();
  }
  /**
   * 生成指定序號(hào)的線(xiàn)程對(duì)象
   *
   * @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;
      }
    };
  }
  /**
   * 生成結(jié)果收集線(xiàn)程對(duì)象
   *
   * @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();
          }
        }
      }
    };
  }
}

運(yùn)行結(jié)果打印和future放入列表時(shí)的順序一致,為0,1,2:

?
1
2
3
4
5
6
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

下面是先執(zhí)行完的線(xiàn)程先處理的方案:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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結(jié)果
   * @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;
  }
}

運(yùn)行結(jié)果為最先結(jié)束的線(xiàn)程結(jié)果先被處理:

?
1
2
3
4
5
6
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

總結(jié)

以上就是本文關(guān)于Java利用future及時(shí)獲取線(xiàn)程運(yùn)行結(jié)果的全部?jī)?nèi)容,希望對(duì)大家有所幫助。有什么問(wèn)題可以隨時(shí)留言,歡迎大家交流討論。

原文鏈接:http://www.cnblogs.com/clarechen/p/4604189.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 中国7777高潮网站 | 久久精品re | 91aa.app | 国产高潮失禁喷水爽到抽搐视频 | 91九色蝌蚪国产 | av日韩在线免费观看 | 黄色电影免费提供 | 狠狠干五月天 | 污视频在线免费播放 | 欧美精品免费一区二区三区 | 日韩精品久久久久久久电影99爱 | 久久久久一区二区三区四区五区 | 黄色片小说 | av观看国产| 黄色片在线观看网站 | 久久夜视频 | 久久人人爽人人爽人人片av高请 | 黄污视频在线看 | 免费国产不卡午夜福在线 | 草久影视| 国产欧美亚洲精品 | 亚洲午夜在线视频 | 关键词 | 欧美一级做一级爱a做片性 91在线视频观看 | 一区二区三区在线观看国产 | 法国性xxx精品hd专区 | 久章草在线观看 | 欧美日韩亚洲另类 | 国产精品久久久久久久久久了 | 欧美激情第一区 | 韩国精品视频在线观看 | 日韩美香港a一级毛片免费 久久精品视频1 | 免费一级毛片在线播放不收费 | 国产在线欧美 | 日韩精品久久久久久久电影99爱 | 成人在线视频播放 | 国内精品久久久久久久久久 | 国产精品久久久久久久久粉嫩 | 欧美成人综合视频 | 国产jjizz一区二区三区视频 | av播放在线 |