java_线程-锁

package com.demo.test3;

import java.util.concurrent.CountDownLatch;

/**
 * @author QQ: 1236897
 *
 */
//闭锁
//nThread - 线程数目
//startGate -确保所有线程就绪-》countDown->所有线程工作
//endGate - 等待所有线程完成工作后才返回timeTask方法
public class CountDownLockTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Caller caller = new Caller();
        MyTask task = new MyTask();

        try {
            System.out.println(caller.timeTask(5, task));
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

class Caller {

    public long timeTask(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++) {
            Thread t = new Thread() {

                public void run() {
                    try {
                        System.out.println("startGate await");
                        startGate.await();
                        try {
                            task.run();
                        } finally {
                            endGate.countDown();
                        }

                    } catch (InterruptedException e) {
                    }
                }

            };

            t.start();
        }

        long start = System.nanoTime();
        System.out.println("startGate countDown");
        startGate.countDown();
        endGate.await();
        long end = System.nanoTime();
        System.out.println("return");
        return end - start;
    }

}

class MyTask implements Runnable {

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("id sleep: - " + Thread.currentThread().getId());
        try {
            Thread.sleep(5000);
            System.out.println("Sleep done: - "
                    + Thread.currentThread().getId());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            Thread.currentThread().interrupt();
        }
    }

}
原文地址:https://www.cnblogs.com/MarchThree/p/4769858.html