public class CountDownLatchTest {
@Test
public void ThreadControllTest() throws InterruptedException{
// Suppose we have total 10 thread waiting to execute
final int TOTAL_THREAD_NUM = 10;
// Leverage our system that only allow 5 threads are running in the same time.
final int COUNT_LATCH = 5;
// The threads control tool that can control how many threads can runnning at same time.
CountDownLatch countDownLatch = null;
for( int i=0; i<TOTAL_THREAD_NUM; i++ ){
Thread.sleep(1000); // give much time gap to see the running results.
// initialize the CounDownLatch Object by COUNT_LATCH gaps.
if( i % 5 == 0 || i == 0){
countDownLatch = new CountDownLatch(COUNT_LATCH);
}
Thread thread = new MockThread(countDownLatch);
thread.start();
}
}
}
class MockThread extends Thread{
CountDownLatch _latch;
public MockThread(CountDownLatch latch){
_latch = latch;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
System.out.println("Thread initial, waiting~~~");
// waiting here and reduce 1 for the COUNT_LATCH num.
// Until COUNT_LATCH has reduce to 0, continue.
_latch.countDown();
_latch.await();
System.out.println("Thread started, starting~~~");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}