关闭

初识java.util.concurrent.CountDownLatch

30人阅读 评论(0) 收藏 举报
分类:
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;
}
}
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:76次
    • 积分:20
    • 等级:
    • 排名:千里之外
    • 原创:2篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档