`

jdk1.5的CountDownLatch同步工具

阅读更多
package cn.com.songjy.test.socket.thread;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * ClassName:CountdownLatchTest 
 * jdk1.5的CountDownLatch同步工具
 * 
 * 主线程(裁判员发令)先运行(cdOrder.countDown()),其它线程(运动员)等待(裁判发令)(cdAnswer.await())
 * 主线程(裁判员发令)完毕后通知其他线程(运动员)运行(cdAnswer.countDown()),主线程(裁判员)等待(运动员)运行结果(cdOrder.await())
 * @author songjy
 * @version 1.0
 * @since v1.0
 * @Date 2013-8-26 下午9:34:54
 */
public class CountdownLatchTest {

	private static Log log = LogFactory.getLog(CountdownLatchTest.class);

	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		final CountDownLatch cdOrder = new CountDownLatch(1);
		final CountDownLatch cdAnswer = new CountDownLatch(3);
		for (int i = 0; i < 3; i++) {
			Runnable runnable = new Runnable() {
				public void run() {
					try {
						log.info("线程" + Thread.currentThread().getName()
								+ "正准备接受命令");
						cdOrder.await();
						log.info("线程" + Thread.currentThread().getName()
								+ "已接受命令");
						Thread.sleep((long) (Math.random() * 10000));
						log.info("线程" + Thread.currentThread().getName()
								+ "回应命令处理结果");
						cdAnswer.countDown();
					} catch (Exception e) {
						log.error(e.getMessage(), e);
					}
				}
			};
			service.execute(runnable);
		}
		try {
			Thread.sleep((long) (Math.random() * 10000));

			log.info("线程" + Thread.currentThread().getName() + "即将发布命令");
			cdOrder.countDown();
			log.info("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果");
			cdAnswer.await();
			log.info("线程" + Thread.currentThread().getName() + "已收到所有响应结果");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		service.shutdown();

	}
}


java 多线程 CountDownLatch用法
闭锁CountDownLatch与栅栏CyclicBarrier
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics