package com.sohu.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
/**
* @author qiaowang
* @date 2013-12-26 上午10:39:01
*/
public class TestThreadDemo {
private ExecutorService exec;
private int cpuNum;
private List<Future<Long>> tasks = new ArrayList<Future<Long>>();
class SumCalculator implements Callable<Long> {
private int[] numbers;
private int start;
private int end;
public SumCalculator(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 TestThreadDemo() {
cpuNum = Runtime.getRuntime().availableProcessors();
exec = Executors.newFixedThreadPool(cpuNum);
}
public Long sum(final int[] numbers) {
// 根据CPU核心个数拆分任务,创建FutureTask并提交到Executor
System.out.println(cpuNum);
for (int i = 0; i < cpuNum; i++) {
int increment = numbers.length / cpuNum + 1;
int start = increment * i;
int end = increment * i + increment;
if (end > numbers.length)
end = numbers.length;
SumCalculator subCalc = new SumCalculator(numbers, start, end);
FutureTask<Long> task = new FutureTask<Long>(subCalc);
tasks.add(task);
if (!exec.isShutdown()) {
exec.submit(task);
}
}
return getResult();
}
public Long getResult() {
Long result = 0l;
for(Future<Long> task : tasks){
try {
Long subSum = task.get();
result +=subSum;
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public void close(){
exec.shutdown();
}
public static void main(String args[]){
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ,12};
TestThreadDemo calc = new TestThreadDemo();
Long sum = calc.sum(numbers);
System.out.println(sum);
calc.close();
}
}
参见
http://www.iteye.com/topic/366591
Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。
public static ExecutorService newFixedThreadPool(int nThreads)
创建固定数目线程的线程池。
public static ExecutorService newCachedThreadPool()
创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。
public static ExecutorService newSingleThreadExecutor()
创建一个单线程化的Executor。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。