一、併發程序
/**
* 高併發測試:
* 建立threadNum個線程;
* 執行任務task
* @param threadNum 線程數量
* @param task 任務
*/
public static void parallelTesk(int threadNum, Runnable task){
// 1. 定義閉鎖來攔截線程
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadNum);
// 2. 建立指定數量的線程
for (int i = 0; i <threadNum; i++) {
Thread t = new Thread(() -> {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException e) {
}
});
t.start();
}
// 3. 線程統一放行,並記錄時間!
long start = System.nanoTime();
startGate.countDown();
try {
endGate.await();
} catch (InterruptedException e) {
}
long end = System.nanoTime();
System.out.println("cost times :" +(end - start));
}
二、應用
import java.util.concurrent.CountDownLatch;
public class Main {
/**
* 定義一個不安全方法:在高併發狀況下得不到想要的結果
* queryTimes 是一個不安全的屬性;
* getTimes是一個不安全方法;
*/
static int queryTimes = 0;
public static int getTimes(){
queryTimes = queryTimes +1;
return queryTimes;
}
/**
* 200個線程來執行獲取getTimes
* @param args
*/
public static void main(String[] args) {
parallelTesk(200, new Runnable() {
@Override
public void run() {
System.out.println(getTimes());
}
});
}
/**
* 高併發測試:
* 建立threadNum個線程;
* 執行任務task
* @param threadNum 線程數量
* @param task 任務
*/
public static void parallelTesk(int threadNum, Runnable task){
// 1. 定義閉鎖來攔截線程
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(threadNum);
// 2. 建立指定數量的線程
for (int i = 0; i <threadNum; i++) {
Thread t = new Thread(() -> {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException e) {
}
});
t.start();
}
// 3. 線程統一放行,並記錄時間!
long start = System.nanoTime();
startGate.countDown();
try {
endGate.await();
} catch (InterruptedException e) {
}
long end = System.nanoTime();
System.out.println("cost times :" +(end - start));
}
}