CountDownLatch

用法一

 

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();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值