1-100求和 递归+线程池

本文介绍了一个使用Java实现的递归任务,通过线程池技术将1到100的整数求和。利用`RecursiveThreadPoolExecutor`,任务被分解为子任务并发执行,最后汇总结果。核心和最大线程数动态调整,确保高效并发。
摘要由CSDN通过智能技术生成

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());
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值