用法一
package com.test.thread;
import java.util.concurrent.CountDownLatch;
/**
* 线程执行类一
*
* @author yangjiasheng
* @version [版本号, 2012-1-30]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class Driver
{
/**
* 线程执行类
* @param args args
* @throws InterruptedException InterruptedException
* @see [类、类#方法、类#成员]
*/
public static void main(String[] args)
throws InterruptedException
{
int n = 5;
CountDownLatch startSignal = new CountDownLatch(1);
CountDownLatch doneSignal = new CountDownLatch(n);
for (int i = 0; i < n; ++i)
{
// create and start threads
new Thread(new Worker(startSignal, doneSignal)).start();
}
doSomethingElse("开始"); // don't let run yet
startSignal.countDown(); // let all threads proceed
doneSignal.await(); // wait for all to finish
doSomethingElse("结束");
}
/**
* <一句话功能简述>
* <功能详细描述>
* @param s s
* @see [类、类#方法、类#成员]
*/
public static void doSomethingElse(String s)
{
System.out.println(s);
}
}
/**
* <一句话功能简述>
* <功能详细描述>
*
* @author yangjiasheng
* @version [版本号, 2012-1-30]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
class Worker implements Runnable
{
private final CountDownLatch startSignal;
private final CountDownLatch doneSignal;
Worker(CountDownLatch startSignal, CountDownLatch doneSignal)
{
this.startSignal = startSignal;
this.doneSignal = doneSignal;
}
public void run()
{
try
{
startSignal.await();
doWork();
doneSignal.countDown();
}
catch (InterruptedException ex)
{
// return;
ex.printStackTrace();
}
}
public void doWork()
{
for (int i = 0; i < 100; i++)
{
System.out.print(i);
}
System.out.println();
}
}