ExecutorService & Callable实现多线程执行并取得每个线程的值

用ExecutorService运行多线程, 实现Callable接口,执行并取得每个线程的值的场景,如下图所示: 在此输入图片描述

代码如下: package com.xue.gang;

import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask;

public class FutureTaskRunnerMutiExecutor {

public static void main(String args[]) throws InterruptedException, ExecutionException{
	
	int size = 100;
	List<FutureTask>  list= new ArrayList<FutureTask>();
	ExecutorService executorService = Executors.newCachedThreadPool();
	//ExecutorService executorService = Executors.newFixedThreadPool(size);
	//协调线程之间
	CountDownLatch countDownLatch = new CountDownLatch(size);
	
	for(int i =1;i<=size;i++){
		System.out.println("---------run index is : " + i);
		FutureTask futureTask = new FutureTask<Object>(new RunnerCallable(i,countDownLatch));
		executorService.execute(futureTask);
		list.add(futureTask);
	}
	
	countDownLatch.await();
	
	for(FutureTask ft:list){
		System.out.println("=============ft get is : " + ft.get());
	}
	//如果不关闭,需要等待超时.
	executorService.shutdown();
}

} /*业务代码/ class RunnerCallable implements Callable<Object>{

private int sumto=0;
private CountDownLatch countDownLatch;


public Object call() throws Exception {
	int sum=0;
	for(int i =0;i<this.sumto;i++){
		sum +=i;
		System.out.println(Thread.currentThread().getId() + "_index is : " + i);
	}
	//减一
	countDownLatch.countDown();
	return  sum;
}


public RunnerCallable(int sumto, CountDownLatch countDownLatch) {
	super();
	this.sumto = sumto;
	this.countDownLatch = countDownLatch;
}

}

转载于:https://my.oschina.net/u/177808/blog/165282

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值