歡迎大家評論區交流
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class ConcurrentTestUtils {
/**
* @param run 要測驗的代碼
* @param threadSize 每次并發的執行緒數
* @param loop 測驗次數
* @Author AmazingMud
*/
public static void execute(Runnable run,int threadSize,int loop){
AtomicInteger count = new AtomicInteger();
for (int j = 0; j <loop ; j++) {
System.out.println("第"+(j+1)+"輪并發測驗,每輪并發數"+threadSize);
CountDownLatch countDownLatch = new CountDownLatch(1);
Set<Thread> threads = new HashSet<>(threadSize);
//批量新建執行緒
for (int i = 0; i <threadSize ; i++) {
threads.add(
new Thread(()->{
try {
countDownLatch.await();
run.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"Thread"+count.getAndIncrement()));
}
//開啟所有執行緒并確保其進入Waiting狀態
for (Thread thread : threads) {
thread.start();
while(thread.getState() != Thread.State.WAITING);
}
//喚醒所有在countDownLatch上等待的執行緒
countDownLatch.countDown();
//等待所有執行緒執行完畢,開啟下一輪
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void execute(Runnable run){
execute(run,1000,1);
}
public static void execute(Runnable run,int threadSize){
execute(run,threadSize,1);
}
public static void main(String[] args) {
execute(()->{
System.out.println(Thread.currentThread());
},10,10);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/404334.html
標籤:其他
上一篇:介面自動化測驗工具- 進階篇:postman 資料驅動
下一篇:Android:訪問存盤失敗.FileNotFoundException open failed: XXXXXXX EPERM (Operation not permitted)
