初识java.util.concurrent.CountDownLatch
package learn;


import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CountDown {
public static int num = 10;
public static void main(String[] args) throws InterruptedException {
//所有任务线程执行结束信号
CountDownLatch doneSignal = new CountDownLatch(num);
//任务执行信号
CountDownLatch startSignal = new CountDownLatch(1);

ExecutorService service = Executors.newCachedThreadPool();
for (int i = 1; i <= num; i++)
{
service.submit(new Worker(doneSignal, startSignal, i));
}

System.out.println("begin ***********************");
//任务开始执行
startSignal.countDown();
//等待所有任务执行结束
doneSignal.await();
service.shutdown();
System.out.println("Done ***********************");
}

static class Worker implements Callable<Object>
{
private CountDownLatch doneSignal;
private CountDownLatch startSignal;
private int index;


Worker(CountDownLatch doneSignal, CountDownLatch startSignal, int index)
{
this.doneSignal = doneSignal;
this.startSignal = startSignal;
this.index = index;
}

@Override
public Object call() 
{
try 
{
//等待任务执行信号
startSignal.await();
for (int i = (index - 1) * 10 + 1; i <= index * 10; i++)
{
System.out.println("worker(" + index + ") print " + i);
}

catch (InterruptedException e) {
e.printStackTrace();
}
finally
{
//任务执行结束信号
doneSignal.countDown();
}

return null;
}
}
}
阅读更多
个人分类: learn
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

初识java.util.concurrent.CountDownLatch

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭