Android之CountDownLatch线程同步

CountDownLatch,它维护一个计数器,等待这个CountDownLatch的线程必须等到计数器为0时才可以继续。 测试代码如下:

public class CountDownLatchTest {
	/**
	 * 启动服务器
	 */
	public static void startServer() throws Exception {
		System.out.println("Server is starting.");
		final CountDownLatch latch = new CountDownLatch(1);
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(" Start thread 1");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(" End thread 1");
				latch.countDown();
			}
		}).start();
		latch.await();
		new Thread(new Runnable() {

			@Override
			public void run() {
				System.out.println(" Start thread 2");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(" End thread 2");
			}
		}).start();
		System.out.println("Server is end!");
	}

	public static void main(String[] args) throws Exception {
		CountDownLatchTest.startServer();
	}
}

运行结果如下:

Server is starting.
 Start thread 1
 End thread 1
Server is end!
 Start thread 2
 End thread 2


由上分析,程序首先运行Thread1.并

latch.await();
这时候,当前线程将被进出等待状态,直到latch 中的计数器转减少成0为止。 CountDownLatch中提供了

countDown()
来减少计数器。当计数器的减少到0 的时候,当前线程将被唤醒,所以执行Thread2.





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值