模擬高併發的狀況java
在多線程編程裏,CountDownLatch是一個很好的計數器工具。編程
它所在的包:多線程
package java.util.concurrent併發
經常使用的兩個方法:ide
一、計數器減一高併發
public void countDown() {工具
sync.releaseShared(1);ui
}this
二、線程等待,在計算器未到達0以前會一直等待.net
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
好,下面來演示兩個demo.
一、等待全部子線程執行完成後再執行主線程的狀況
二、模擬高併發的狀況
代碼以下:
package com.figo.study.test;
import java.util.concurrent.CountDownLatch;
/**
* test CountDownLatch
* @author figo
* 20180605.
*/
public class TestSomething {
public static void main(String[] args) {
//testWaitThread();
testConcurrent();
}
/**
* 一、模擬全部子線程都執行完成後再執行主線程
* countdownLatch計數,模擬子線程執行完成以後再執行主線程
* 這個也能夠用future來實現
*
*/
public static void testWaitThread()
{
final CountDownLatch latch = new CountDownLatch(2);
new Thread(){
public void run() {
try {
System.out.println("子線程"+Thread.currentThread().getName()+"正在執行");
Thread.sleep(3000);
System.out.println("子線程"+Thread.currentThread().getName()+"執行完畢");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
new Thread(){
public void run() {
try {
System.out.println("子線程"+Thread.currentThread().getName()+"正在執行");
Thread.sleep(3000);
System.out.println("子線程"+Thread.currentThread().getName()+"執行完畢");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
try {
System.out.println("等待2個子線程執行完畢...");
latch.await();
System.out.println("2個子線程已經執行完畢");
System.out.println("繼續執行主線程");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 線程數量
*/
public static final int THREAD_NUM = 100;
/**
* 開始時間
*/
private static long startTime = 0L;
/**
* 二、模擬高併發
*/
public static void testConcurrent()
{
try {
startTime = System.currentTimeMillis();
System.out.println("CountDownLatch started at: " + startTime);
// 初始化計數器爲1
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 0; i < THREAD_NUM; i ++) {
new Thread(new Run(countDownLatch)).start();
}
// 啓動多個線程
countDownLatch.countDown();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
/**
* 線程類
*/
private static class Run implements Runnable {
private final CountDownLatch startLatch;
public Run(CountDownLatch startLatch) {
this.startLatch = startLatch;
}
@Override
public void run() {
try {
// 線程等待
startLatch.await();
// 模擬耗時操做
Thread.sleep(3000);
long endTime = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + " ended at: " + endTime + ", cost: " + (endTime - startTime) + " ms.");
} catch (Exception e) {
e.printStackTrace();
}
}
}