JAVA线程池与CountDownLatch结合使用DEMO版

本文写一个线程池与CountDownLatch结合例子,主任务先行开始,打印出开始执行时间,等待n(demo设置的为5)个子任务执行完毕,进行后续打印操作。附上源码,仅供学习了解所用。

具体处理事务的子任务类:

package com.gll.basic.multi;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 
 * @author LynnGe
 *
 */
public class CounterTask implements Runnable {
	private CountDownLatch latch;
	private List countList;

	public CounterTask(CountDownLatch latch, List countList) {
		this.latch = latch;
		this.countList = countList;
	}

	@Override
	public void run() {
		try {
			//doSomeThing....
			countList.add(new Integer(1));
		} finally {
			if (latch != null) {
				latch.countDown();
			}
		}
	}

}

 

测试主类

package com.gll.basic.multi;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author LynnGe
 *
 */
public class ThreadPoolDemo {
	static ExecutorService taskPool = Executors.newFixedThreadPool(6);

	public static void main(String[] args) throws Exception {
		int waitTimes = 5;
		CountDownLatch latch = new CountDownLatch(waitTimes);
		List rlt = new ArrayList();
		new WaitingThread(latch).start();
		//创建任务的次数和等待的次数相等
		for (int i = 0; i < waitTimes; i++) {
			taskPool.execute(new CounterTask(latch, rlt));
		}
		Integer sum = 0;
		for (Integer i : rlt) {
			sum += i;
		}
		System.out.println("sum:: " + sum);
		// 任务全部执行完毕,所以获取的为0
		System.out.println("latch:: " + latch.getCount());
		System.out.println("taskPool shutdown flag:: " + taskPool.isShutdown());
		//立即关闭线程池
		taskPool.shutdownNow();//中断线程池中所有线程,实际使用中慎用
		System.out.println("taskPool shutdown flag:: " + taskPool.isShutdown());

	}

	static class WaitingThread extends Thread {
		CountDownLatch countDownLatch;

		public WaitingThread(CountDownLatch countDownLatch) {
			this.countDownLatch = countDownLatch;
		}

		@Override
		public void run() {
			System.out.println(System.nanoTime() + " 等待  " + countDownLatch.getCount() + " 个子任务执行开始");
			try {
				countDownLatch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(System.nanoTime() + " 等待结束");
		}
	}

}

运行结果 :

JAVA线程池与CountDownLatch结合使用DEMO版_第1张图片

 

你可能感兴趣的:(Java学习)