标签: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
标签:tst imp trace vat lis author tac inter pac
原文地址:https://www.cnblogs.com/gaopengpy/p/12737013.html