服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - Java实现Promise.all()的示例代码

Java实现Promise.all()的示例代码

2021-05-24 14:02SevenLin1993 Java教程

这篇文章主要介绍了Java实现Promise.all()的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

javascript的promise.all()

promise是javascript异步编程的一种解决方案,在es6中引入。

通过promise.all()可以实现对一组异步请求的统一处理,等待所有异步执行完成之后调用回调函数。

其实,这种并发执行同步等待的需求在java并发编程中也很常见,那么,是否可以通过java也来实现这样一个promise类呢?

使用java实现promise.all()

使用工具

countdownlatch:java并发工具包中有countdownlatch类允许一个或多个线程等待其他线程的一系列操作完成。

threadpoolexecutor:通过线程池实现多线程的并发执行

实现

?
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
public class promise {
 
  private static executorservice executorservice = executors.newscheduledthreadpool(16);
 
  private promise() {
    throw new assertionerror();
  }
 
  /**
   * 实现并发同时地对某个action并发执行并返回执行结果
   * 实现思路:
   * 并发创建所有执行的线程,并通过锁(start)阻塞等待着
   * 在创建所有执行的线程后(ready)开始计时,并解锁然所有的线程启动
   * 通过另外一个锁(done)记录执行完的线程
   * 主线程只需关心3点
   * - 所有线程是否准备好
   * - 准备好的话开始计时并解锁开始执行
   * - 等待执行完毕
   *
   * @param callablelist 要并发执行的列表
   * @return list 执行结果,list.item为null的话表示执行异常
   * @throws interruptedexception 异常
   */
  public static <t> list<t> all(final list<callable<t>> callablelist) throws interruptedexception {
    final list<t> result = new arraylist<>();
    int length = callablelist.size();
    final countdownlatch ready = new countdownlatch(length);
    final countdownlatch start = new countdownlatch(1);
    final countdownlatch done = new countdownlatch(length);
    for (final callable<t> callable : callablelist) {
      executorservice.execute(new runnable() {
        @override
        public void run() {
          ready.countdown();
          try {
            start.await();
            t t = callable.call();
            result.add(t);
          } catch (exception e) {
            // interrupt when exception
            thread.currentthread().interrupt();
            // set null mean exception
            result.add(null);
            e.printstacktrace();
          } finally {
            done.countdown();
          }
        }
      });
    }
    ready.await();
    long startnano = system.nanotime();
    start.countdown();
    done.await();
    long cause = system.nanotime() - startnano;
    system.out.println(string.format("promise all done,cause time millsecond: %s", cause / 1000000));
    return result;
  }
}

效果

测试

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void promisealltest() throws exception{
 
  list<callable<string>> callables = new arraylist<>();
 
  for (int i = 0; i < 10; i++) {
    int finali = i;
    callables.add(new callable<string>() {
      @override
      public string call() throws exception {
        int millis = new random().nextint(10000);
        thread.sleep(millis);
        system.out.println(string.format("thread%s sleep %s millis" ,finali,millis));
        return "thread" + finali;
      }
    });
  }
 
  list<string> result = promise.all(callables);
 
  system.out.println(result);
  system.out.println("done...");
 
}

测试结果

thread1 sleep 732 millis
thread2 sleep 758 millis
thread7 sleep 976 millis
thread8 sleep 1397 millis
thread5 sleep 1513 millis
thread0 sleep 2221 millis
thread3 sleep 4885 millis
thread6 sleep 5221 millis
thread4 sleep 7101 millis
thread9 sleep 7634 millis
promise all done,cause time millsecond: 7638
[thread1, thread2, thread7, thread8, thread5, thread0, thread3, thread6, thread4, thread9]
done...

总结

本文只是通过原生java实现简单版本的promise.all(),可用于简单的并发编程,但是对于实际高并发应用还需要优化,如对线程池的优化,还有中断的处理等。

参考

《effective java》第二版第十章第69条:并发工具优先于wait和notify

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.jianshu.com/p/047a2d161f01

延伸 · 阅读

精彩推荐