CountDownLatch実戦


背景:単一スレッドでloaderを起動し、loaderでマルチスレッド計算を行う
1.単線からloader、省略
2.マルチスレッドloaderコード,AbstractDataCounterLoader起動スレッド,runメソッドではcalcを抽象化してサブクラスに実装する
public class MutiThreadLoader extends AbstractDataCounterLoader {
	private static final Logger logger = LoggerFactory.getLogger(MutiThreadLoader.class);

	/**
	 *  
	 */
	private int mutiThreadNum = 0;
	
	/**
	 *  
	 */
	private String handlerClassName;

	@Override
	protected boolean calc() {

		if (mutiThreadNum < 1) {
			return false;
		}
		CountDownLatch countDownLatch = new CountDownLatch(mutiThreadNum);
		List<AbstractHandler> mutiThreadLoaders = getMutiThreadLoaders(countDownLatch,
				mutiThreadNum);
		if (null == mutiThreadLoaders){
			return false;
		}
		ExecutorService exec = Executors.newFixedThreadPool(mutiThreadNum);
		for (int i = 0; i < mutiThreadNum; i++) {
			exec.submit(mutiThreadLoaders.get(i));
		}
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			logger.error("InterruptedException:", e);
		}
		exec.shutdown();
		System.out.println("end");
		
		return true;
	}

	protected List<AbstractHandler> getMutiThreadLoaders(CountDownLatch countDownLatch,
			int mutiThreadNum) {
		List<AbstractHandler> mutiThreadLoaders = new ArrayList<AbstractHandler>();
		for (int i = 0; i < mutiThreadNum; i++) {
			AbstractHandler handler = getHandler();
			if (null == handler){
				return null;
			}
			handler.setThreadNum(i);
			handler.setCountDownLatch(countDownLatch);
			mutiThreadLoaders.add(handler);
		}
		return mutiThreadLoaders;
	}

	//  
	protected AbstractHandler getHandler(){
		AbstractHandler handler = null;
		try {
			handler = (AbstractHandler) Class.forName(handlerClassName).newInstance();
		} catch (InstantiationException e) {
			logger.error("getHandler error",e);
		} catch (IllegalAccessException e) {
			logger.error("getHandler error",e);
		} catch (ClassNotFoundException e) {
			logger.error("getHandler error",e);
		}
		return handler;
	}

	public int getMutiThreadNum() {
		return mutiThreadNum;
	}

	public void setMutiThreadNum(int mutiThreadNum) {
		this.mutiThreadNum = mutiThreadNum;
	}

	public String getHandlerClassName() {
		return handlerClassName;
	}

	public void setHandlerClassName(String handlerClassName) {
		this.handlerClassName = handlerClassName;
	}

}

2.spring構成
Xml構成例:

                  
                  
                  
                  
       

                  
                  
        

3.ビジネス実装クラスはcomloader.を継承する必要がある.muti.AbstraactHandler実装executeメソッド

public class HandlerTest extends AbstractHandler{

	@Override
	protected void execute(int threadNum) {
		try {
			Thread.currentThread().sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("---" + threadNum);
	}

}