Java 并发包及其常用类

并发包体系结构:

 1. CountDownLatch

CountDownLatch 是一个同步工具类,用来协调多个线程之间的同步。
CountDownLatch 通过计数器来实现:使一个线程在等待另外一些线程完成各自工作后,再执行。计数器初始值为线程的数量。当每一个线程完成自己任务后,就通过 countDown()方法 将计数器减1。当计数器的值减为0时,表示其他所有线程都已经完成了各自的一些任务,然后在 CountDownLatch 上等待的线程就可以恢复执行接下来的任务。

方法源码:

/* @param count the number of times {@link #countDown} must be invoked
     *        before threads can pass through {@link #await}
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }
/* Causes the current thread to wait until the latch has counted down to
 * zero, unless the thread is {@linkplain Thread#interrupt interrupted}.

 * @throws InterruptedException if the current thread is interrupted
 *         while waiting  */
public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

/**
 * Causes the current thread to wait until the latch has counted down to
 * zero, unless the thread is {@linkplain Thread#interrupt interrupted},
 * or the specified waiting time elapses.  */
public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

示例:

public class Test {
    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3,3,10, TimeUnit.SECONDS,new LinkedBlockingDeque<Runnable>());
        CountDownLatch latch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("子线程"+Thread.currentThread().getName()+"执行完成");
                    latch.countDown();    //当前线程调用此方法,计数减一
                }
            });
        }
        {
            System.out.println("主线程" + Thread.currentThread().getName() + "等待子线程执行完成...");
            latch.await();//阻塞当前线程,直到计数器的值为0
            System.out.println("主线程" + Thread.currentThread().getName() + "开始执行...");
        }
    }

}

 

未完待续~

 

 

 

©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页