import java.util.concurrent.CountDownLatch;
public class ThreadOnOffGate
{
public static void main(String str[]) throws InterruptedException{
int N = 10000 ;
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();
System.out.println ("Main Thread will wait here") ;
startSignal.countDown(); // let all threads proceed
System.out.println(" Main thread waiting");
doneSignal.await(); // wait for all to finish
System.out.println(" Main thread work done.") ;
}
}
class Worker implements Runnable {
private CountDownLatch startCountDownLatch;
private CountDownLatch doneCountDownLatch;
Worker(CountDownLatch start, CountDownLatch done){
this.startCountDownLatch = start ;
this.doneCountDownLatch = done ;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
@Override
public void run()
{
try {
startCountDownLatch.await() ;
doWork() ;
doneCountDownLatch.countDown() ;
}catch(InterruptedException e){
}
}
/**
*
*/
private void doWork()
{
System.out.println("Current Thread : " + Thread.currentThread().getName() + " working") ;
}
}
No comments:
Post a Comment