码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2020-04-20 13:46:19      阅读:56      评论:0      收藏:0      [点我收藏+]

标签:tst   imp   trace   vat   lis   author   tac   inter   pac   

使用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模拟线程并发执行代码

标签:tst   imp   trace   vat   lis   author   tac   inter   pac   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!