1-100求和 递归+线程池
public class Test {
static int coreSize = Runtime.getRuntime().availableProcessors() + 1;
static RecursiveThreadPoolExecutor executor = new RecursiveThreadPoolExecutor(coreSize, coreSize << 1,
60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
static CountDownLatch countDownLatch = new CountDownLatch(50);
public static void main(String[] args) throws InterruptedException {
executor.submit(new Task(1, 100));
countDownLatch.await();
executor.shutdown();
}
static class Task implements Callable<Integer> {
int start;
int end;
public Task(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Integer call() throws Exception {
if (end - start > 1) {
int mid = (start + end) / 2;
executor.submit(new Task(start, mid));
executor.submit(new Task(mid + 1, end));
} else if (start == end){
System.out.println("start: " + start + "---- end: " + end);
countDownLatch.countDown();
System.out.println("门栓数量:" + countDownLatch.getCount());
return start;
}else {
System.out.println("start: " + start + "---- end: " + end);
countDownLatch.countDown();
System.out.println("门栓数量:" + countDownLatch.getCount());
return start + end;
}
return 0;
}
}
static class RecursiveThreadPoolExecutor extends ThreadPoolExecutor {
AtomicInteger sum = new AtomicInteger(0);
public RecursiveThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
if (r instanceof Future) {
try {
Future<Integer> f = (Future<Integer>) r;
sum.addAndGet(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
@Override
protected void terminated() {
System.out.println("####### 计算结果是: " + sum.get());
}
}
}