博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CompletionService实例-Mine
阅读量:2351 次
发布时间:2019-05-10

本文共 2334 字,大约阅读时间需要 7 分钟。

package com.bugyun.test;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;public class MyCompletionService {		private ExecutorService executorService;	private CompletionService
completionService; private int cpuCoreNumber; public MyCompletionService() {// 获取当前系统的CPU 数目 cpuCoreNumber = Runtime.getRuntime().availableProcessors();// ExecutorService通常根据CPU数目定义线程池大小 executorService = Executors.newFixedThreadPool(cpuCoreNumber);// 更高级的ExecutorService completionService = new ExecutorCompletionService
(executorService); } /** * 将任务分配给子任务执行 */ public Long statistic(final int[] numbers) { int size = numbers.length; for (int i = 0; i < cpuCoreNumber; i++) { int increment = size / cpuCoreNumber + 1; int start = increment * i; int end = increment * (i + 1); if (end > size){ end = size; } Task task = new Task(numbers, start, end); if(!executorService.isShutdown()){ completionService.submit(task); } } return getResult(); } /** * 遍历子任务,获取结果 */ public Long getResult() { Long result = 0l; for (int i = 0; i < cpuCoreNumber; i++) { try { Long subSum = completionService.take().get(); System.out.println(" ===> 获取结果的核是:"+i+" , 此时结果为:"+subSum); result += subSum; } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } return result; } public void close() { executorService.shutdown(); } class Task implements Callable
{ private int[] numbers; private int start; private int end; public Task(final int[] numbers, int start, int end) { this.numbers = numbers; this.start = start; this.end = end; } public Long call() throws Exception { Long sum = 0l; for (int i = start; i < end; i++) { sum += numbers[i]; } return sum; } } public static void main(String... args) throws Exception { int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; MyCompletionService myCompletion = new MyCompletionService(); Long result = myCompletion.statistic(numbers); System.out.println("最终结果是:"+result); myCompletion.close(); }}

 

 运行结果:

 

转载地址:http://jrevb.baihongyu.com/

你可能感兴趣的文章
08.桥接模式--Bridge
查看>>
09.适配器模式--Adapter
查看>>
10.装饰模式--Decorator
查看>>
11.组合模式--Composite
查看>>
12.轻量模式--Flyweight
查看>>
13.外观模式--Facade
查看>>
14.代理模式--Proxy
查看>>
15.模板模式--Template
查看>>
16.策略模式--Strategy
查看>>
开源史上最成功的八个开源软件
查看>>
More Effective C++读书笔记
查看>>
关于assert,ASSERT,TRACE和VERIFY
查看>>
关于C++中野指针的说明
查看>>
_USRDLL _AFXDLL _WINDLL 三种dll编译宏的具体含义
查看>>
面试中的C++常见问题
查看>>
STL中的string和wstring的格式化方法之一
查看>>
STL中的string和wstring的格式化方法之二
查看>>
socket套接字TCP API说明
查看>>
easyui菜单项的置灰操作
查看>>
js数组的操作
查看>>