使用CountDownLatch模拟线程并发执行代码
2021-02-11 11:18
标签:tst imp trace vat lis author tac inter pac 使用CountDownLatch模拟线程并发执行代码,示例代码如下: 执行结果如下: Thread[Thread-2,5,main] = 1587356721613 使用CountDownLatch模拟线程并发执行代码 标签:tst imp trace vat lis author tac inter pac 原文地址:https://www.cnblogs.com/gaopengpy/p/12737013.htmlpackage 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 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-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模拟线程并发执行代码
文章链接:http://soscw.com/index.php/essay/54001.html