JDK1.5还提供了Callable<T>和Future<T>接口,用于线程池执行任务并获取返回值。下面给出一个简单的示例代码。
1. 实现一个任务

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;
}
}2.使用线程池执行任务并获取返回值

public class ThreadPoolSample ...{

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) ...{
ThreadPoolSample sample = new ThreadPoolSample();
try ...{
sample.count();
} catch (InterruptedException e) ...{
e.printStackTrace();
} catch (ExecutionException e) ...{
e.printStackTrace();
}
}
}
附:自己实现一个线程池
Tomcat的源代码中实现了一个线程池,有兴趣可以看一下。在connectors的util下面。具体目录:org\apache\tomcat\util\threads
1592

被折叠的 条评论
为什么被折叠?



