一个非常有用的类,CountDownLatch, 可以用来在一个线程中等待多个线程完成任务的类;
通常的使用场景是,某个主线程接到一个任务,起了n个子线程去完成,但是主线程需要等待这n个子线程都完成任务了以后才开始执行某个操作;
测试代码如下:
package test;
import java.util.concurrent.CountDownLatch;
public class TestThread {
/**
*
* @author Administrator/2012-3-1/上午09:19:02
*/
public static void main(String[] args) {
TestThread t=new TestThread();
t.demoCountDown();
}
public void demoCountDown()
{
int count = 10;
final CountDownLatch l = new CountDownLatch(count);
for(int i = 0; i < count; ++i)
{
final int index = i;
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.currentThread().sleep(20 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread " + index + " has finished...");
l.countDown();
}
}).start();
}
try {
l.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("now all threads have finished");
}
}
运行结果:
thread 1 has finished...
thread 3 has finished...
thread 0 has finished...
thread 7 has finished...
thread 4 has finished...
thread 9 has finished...
thread 8 has finished...
thread 2 has finished...
thread 6 has finished...
thread 5 has finished...
now all threads have finished
前面10个线程的执行完成顺序会变化,但是最后一句始终会等待前面10个线程都完成之后才会执行.