这可能有点超出你的任务要求你做的界限(不确定你的意思).但这是一个非常基本的例子,说明如何使用固定的线程池解决这个问题.节省您自己管理线程的麻烦.你的#threads将是fixedThreadPool的大小.然后你可以创建添加两个数字的“工作”.如果您有一个奇数上限,在这里只需添加最后一个数字.
private static ExecutorService tpool = Executors.newFixedThreadPool(20);
private static final int upper = 140;
private static AtomicInteger total = new AtomicInteger(0);
public static void main(String[] args) throws Exception {
int ar[] = new int[upper];
for(int i = 1 ; i <= upper; i++){
ar[i-1]=i;
}
for(int i = 1 ; i <= ((upper%2) !=0 ? (upper-1):(upper)); i+=2){
final int a = ar[i-1];
final int b = ar[i];
Thread thread = new Thread(new Runnable(){
public void run() {
int res = add(a, b);
total.addAndGet(res);
return;
}});
tpool.execute(thread);
}
if(upper%2!=0)
total.addAndGet(ar[ar.length-1]);
tpool.shutdown(); //wait for everything to finish
System.out.println(total.get()); //get the result.
}
private static int add(final int a, final int b){
return a+b;
}
可以说,如果您有两个线程读取数组的块,那么效率会降低,因为您会告诉线程1添加1-6而线程2添加7-12.但它基本上做同样的事情,这种方法非常适合更加计算密集的任务.