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.





原创粉丝点击