首页 > 代码库 > 【JAVA并发编程实战】4、CountDownLatch

【JAVA并发编程实战】4、CountDownLatch

这是一个计数锁,说白了,就是当你上锁的时候,只有计数减少到0的时候,才会释放锁

 

package cn.xf.cp.ch05;

public class TaskRunable implements Runnable
{

    @Override
    public void run()
    {
        System.out.println("do something...");
    }
    
    public static void main(String []args)
    {
        Thread t = new Thread(new TaskRunable());
        t.start();
    }
}

 

package cn.xf.cp.ch05;

import java.util.concurrent.CountDownLatch;

/**
 * 
 *功能:10个线程同步
 *时间:下午6:08:46
 *文件:ReadData.java 
 *@author Administrator
 *
 */
public class ReadData
{
//    private static int SEEK_NUM = 0;
    
    //同步运行,并统计时间
    public static long timeTasks(int nThreads, final Runnable task) throws InterruptedException
    {
        //起始门,用来划定线程同步开始的时间
        final CountDownLatch startGate = new CountDownLatch(1);
        //用来等待所有线程结束
        final CountDownLatch endGate = new CountDownLatch(nThreads);
        
        for(int i = 0; i < nThreads; ++i)
        {
            //设置写出文件开始位置,一个long+空格是10个字节
            //创建线程
            Thread t = new Thread()
                                {
                                    public void run()
                                    {
                                        try
                                        {
                                            //等待所有线程启动
                                            startGate.await();
                                            try
                                            {
                                                task.run();//启动线程
                                            }
                                            finally
                                            {
                                                //线程运行结束之后上通知
                                                endGate.countDown();
                                            }
                                        }
                                        catch (InterruptedException e)
                                        {
                                        }
                                    }
                                };
            t.start();
        }
        
        long start = System.nanoTime();
        //使开始门解锁,task开始工作
        startGate.countDown();
        //给end们上锁,只有减少到0才解锁
        endGate.await();
        long end = System.nanoTime();
        
        return end - start; //时间结果
    }
    
    public static void main(String[] args)
    {
        TaskRunable tr = new TaskRunable();
        try
        {
            System.out.println(ReadData.timeTasks(10, tr));
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

 

结果

技术分享

 

【JAVA并发编程实战】4、CountDownLatch