java CountDownLatch的用法

主要可以使用计数来锁和解锁线程
[ccn lang="java" tab_size="4" theme="blackboard" width="550" ]
package com.ohergal.guice.test;

import java.util.concurrent.CountDownLatch;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class TestCountDownLatch {
@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testRun() {
final CountDownLatch startSignal = new CountDownLatch(1);
final CountWapper cw = new CountWapper();
Thread t = new Thread() {
public void run() {
try {
cw.add();
startSignal.await();
cw.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
cw.add();
assertEquals(1,cw.getI());
t.start();
assertEquals(2,cw.getI());
cw.add();
assertEquals(3,cw.getI());
startSignal.countDown();
assertEquals(4,cw.getI());
}
}
[/ccn]
在释放锁之前线程会一直在await()处等待