作家
登录

浅谈Java的Fork/Join并发框架

作者: 来源: 2017-08-04 15:02:12 阅读 我要评论

new ForkJoinPool(); 
  •         ForkJoinService<List<String>> forkJoinService = ForkJoinTest.getInstance(stringList, 20); 
  •         // 提交可分化的ForkJoinTask义务 
  •         ForkJoinTask<List<String>> future = pool.submit(forkJoinService); 
  •         System.out.println(future.get()); 
  •         // 封闭线程池 
  •         pool.shutdown(); 
  •  
  •     } 
  •  
  • 下面是引用Oracle官方定义的原文:

    The fork/join framework is an implementation of the ExecutorService interface that helps you take advantage of multiple processors. It is designed for work that can be broken into smaller pieces recursively. The goal is to use all the available processing power to enhance the performance of your application.

    代码如下:

    As with any ExecutorService implementation, the fork/join framework distributes tasks to worker threads in a thread pool. The fork/join framework is distinct because it uses a work-stealing algorithm. Worker threads that run out of things to do can steal tasks from other threads that are still busy.

    The center of the fork/join framework is the ForkJoinPool class, an extension of the AbstractExecutorService class. ForkJoinPool implements the core work-stealing algorithm and can execute ForkJoinTask processes.

    2. Fork/Join的根本用法

    (1)Fork/Join基类

      上文已经提到,Fork/Join就是要讲一个大年夜的义务瓜分成若干小的义务,所以第一步当然是要做义务的瓜分,大年夜致方法如下:

    1. if (这个义务足够小){ 
    2.   履行要做的义务 
    3. else { 
    4.   将义务瓜分成两小部分 
    5.   履行两小部分并等待履行结不雅 

    要实现FrokJoinTask我们须要一个持续了RecursiveTask或RecursiveAction的基类,并根据自身营业情况将膳绫擎的代码放入基类的coupute办法中。RecursiveTask和RecursiveAction都持续了FrokJoinTask,它俩的差别就是RecursiveTask有返回值而RecursiveAction没有。下面是我做的一个选出字符串列表中还有"a"的元素的Demo:

    1. @Override 
    2. protected List<String> compute() { 
    3.     // 当end与start之间的差小于阈值瓯,开端进行实际筛选 
    4.     if (end - this.start < threshold) { 
    5.         List<String> temp = list.subList(this.start, end); 
    6.         return temp.parallelStream().filter(s -> s.contains("a")).collect(Collectors.toList()); 
    7.     } else { 
    8.         // 如不雅当end与start之间的差大年夜于阈值时 
    9.         // 将大年夜义务分化成两个小义务。 
    10.         int middle = (this.start + end) / 2

    11.   推荐阅读

        Gartner公布2017年全球云存储魔力象限:阿里云跻身四强 全球前四

      图1-2017年Gartner全球云存储魔力象限图 据媒体报道,国际有名调研机构Gartner近日颁布了2017年全球云计算云存储魔力象限。阿里云的云存储成长敏捷,与AWS、Microsoft、Google合营跻身这一>>>详细阅读


      本文标题:浅谈Java的Fork/Join并发框架

      地址:http://www.17bianji.com/lsqh/36553.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)