使用CountDownLatch模拟线程并发执行代码

时间:2020-04-20
本文章向大家介绍使用CountDownLatch模拟线程并发执行代码,主要包括使用CountDownLatch模拟线程并发执行代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

使用CountDownLatch模拟线程并发执行代码,示例代码如下:

package com.gaopeng.multithread;

import java.util.concurrent.CountDownLatch;

/**
 * 使用CountDownLatch模拟线程并发执行代码
 * 
 * @author gaopeng
 *
 */
public class CountDownLatchConTest {

    // 并发数
    private static final int THREAD_NUM = 10;

    private static volatile CountDownLatch countDownLatch = new CountDownLatch(THREAD_NUM);

    public static void main(String[] args) throws InterruptedException {

        for (int i = 0; i < THREAD_NUM; i++) {
            Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    // 所有的线程在这里等待
                    try {
                        countDownLatch.await();
                        System.out.println(Thread.currentThread() + " = " + System.currentTimeMillis());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            });

            thread.start();

            // 启动后,倒计时计数器减一,代表有一个线程准备就绪了
            countDownLatch.countDown();
        }
    }
}

执行结果如下:

Thread[Thread-2,5,main] = 1587356721613
Thread[Thread-1,5,main] = 1587356721613
Thread[Thread-8,5,main] = 1587356721613
Thread[Thread-3,5,main] = 1587356721613
Thread[Thread-7,5,main] = 1587356721613
Thread[Thread-6,5,main] = 1587356721613
Thread[Thread-5,5,main] = 1587356721613
Thread[Thread-0,5,main] = 1587356721613
Thread[Thread-4,5,main] = 1587356721613
Thread[Thread-9,5,main] = 1587356721613

原文地址:https://www.cnblogs.com/gaopengpy/p/12737013.html