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

Posted gaopengpy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用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

以上是关于使用CountDownLatch模拟线程并发执行代码的主要内容,如果未能解决你的问题,请参考以下文章

并发与高并发-并发模拟代码

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

Java并发多线程编程——CountDownLatch

006-多线程-JUC线程池-并发测试程序

java并发中CountDownLatch的使用

Java并发编程--CountDownLatch