多个线程同时开始启动计时框架的设计与实现

在DEMO测试中,我有个需求描述如下:线程A、B、C、D,我需要他们同时开始运行,并记录这四个线程全部完成所需要的时间。


这个借助synchronizer可轻松完成。这里我们使用CountDownLatch来实现,该方法的详细描述参见我的上篇博文:点击打开链接


核心代码如下:demo请参见github

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	private static long timer(Executor e,int concurrency,final Runnable action) throws InterruptedException{
		final CountDownLatch ready = new CountDownLatch(concurrency);
		final CountDownLatch start = new CountDownLatch(1);
		final CountDownLatch end = new CountDownLatch(concurrency);
		
		//将线程同时启动并处于wait状态,知道start.await因为countDown=0被启动
		for(int i=0;i<concurrency;i++){
			e.execute(new Runnable(){

				@Override
				public void run() {
					// TODO Auto-generated method stub
					ready.countDown();
					try {
						start.await();
						System.out.print(Thread.currentThread().getId()+"ready\n");
						action.run();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						Thread.currentThread().interrupt();
					}finally{
						System.out.print(Thread.currentThread().getId()+"end\n");
						end.countDown();
						
					}
				}
				
			});
		}
		ready.await();
		start.countDown();
		long startTime = System.nanoTime();
		end.await();
		return System.nanoTime()-startTime;

调用方法:
public static void main(String[] args) {
		// TODO Auto-generated method stub
		i = new AtomicInteger();
		ExecutorService e = Executors.newFixedThreadPool(5);
		Runnable action = new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					//System.out.print(i.get()+"\n");
					TimeUnit.SECONDS.sleep(i.getAndAdd(5));
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		};
		try {
			long time = timer(e, 4, action);
			System.out.println(time);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		e.shutdown();

	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章