Android之CountDownLatch线程同步
来源:互联网 发布:java上下文是什么意思 编辑:程序博客网 时间:2024/06/05 14:11
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() {@Overridepublic 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() {@Overridepublic 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.
- Android之CountDownLatch线程同步
- 线程同步之CountDownLatch
- java线程同步之CountDownLatch
- 线程同步工具之CountDownLatch
- 线程同步工具之CountDownLatch
- 线程同步工具之CountDownLatch
- 线程同步工具之CountDownLatch
- 线程同步工具之CountDownLatch
- 线程同步工具之CountDownLatch
- 11.5线程----同步装置之CountDownLatch
- 11.5.2线程 同步装置之CountDownLatch
- 线程同步工具之CountDownLatch示例
- CountDownLatch线程同步助手
- 线程同步-CountDownLatch
- 线程同步-CountDownLatch
- 线程同步-CountDownLatch
- 线程同步-CountDownLatch
- 线程同步工具-CountDownLatch
- ubuntu 10.04 NFS配置
- Subversion 安装及配置说明(windows7)
- 使用git建立本地仓储管理代码
- redhat版本介绍
- 任意位置得到Spring bean
- Android之CountDownLatch线程同步
- C 语言 ---- 汉诺塔算法
- 第2章 Model View Controller
- local service and remote service(AIDL Service)
- HBase存储架构
- GetCurrentDirectory(255,buff);SetCurrentDirectory(TEXT("C:\\windows"));
- linux——posix标准下的信号量
- 生命的热情
- 今天就看了二三十页书