一、不带返回值的线程池方法
如果想让他带返回值,需要做一些特殊处理。主要思想如下:
二、带返回值的方法:(http://softstone.javaeye.com/blog/172903)
package cn.edu.xjtu.nhpcc.jenva.threadpool;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestCall2 {
float[][] scores = { { 87, 86, 90, 91, 76 }, { 56, 34, 66, 78, 65 },
{ 99, 97, 95, 87, 89 }, { 77, 76, 75, 78, 85 },
{ 88, 56, 78, 78, 76 } };
Future<Float>[] result = new Future[5];
public void count() throws InterruptedException, ExecutionException {
//创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
for (int i = 0; i < scores.length; i++) {
//提交任务,获取结果
result[i] = pool.submit(new Caller(scores[i]));
}
for (int i = 0; i < result.length; i++){
System.out.println(result[i].get());
}
//关闭线程池
pool.shutdown();
}
public static void main(String[] args) {
TestCall2 sample = new TestCall2();
try{
sample.count();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class Caller implements Callable<Float> {
private float[] score;
public Caller(float[] score){
this.score = score;
}
/** *//**
* 计算平均分
*/
public Float call() throws Exception {
float sum = 0;
for (int i=0;i<score.length;i++){
sum+=score[i];
}
return sum/score.length;
}
}
}