[并发编程]并发辅助类CountDownLatch使用

构造器: public CountDownLatch(int count) {};  //参数count为计数值

3个方法是CountDownLatch类中最重要的方法:
	public void await() throws InterruptedException { };   //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
	public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };  //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
	public void countDown() { };  //将count值减1
	
package design_pattern;

import java.util.concurrent.CountDownLatch;

import design_pattern.singleton.HungryPattern;

public class CountDownLatchTest {

	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(2);
		System.out.println("程序开始...............");

		new Thread() {
			@Override
			public void run() {
				System.out.println("程序进入线程1...............");
				Object instance = HungryPattern.getInstance();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(System.currentTimeMillis() + ":" + instance);
				latch.countDown();
			}
		}.start();

		new Thread() {
			@Override
			public void run() {
				System.out.println("程序进入线程2...............");
				Object instance = HungryPattern.getInstance();
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(System.currentTimeMillis() + ":" + instance);
				latch.countDown();
			}
		}.start();

		try {
			System.out.println("程序等待...............");
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("程序结束...............");
	}

}
程序开始...............
程序进入线程1...............
程序等待...............
程序进入线程2...............
1548513253701:java.lang.Object@5a07ae42
1548513253701:java.lang.Object@5a07ae42
程序结束...............

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值