多线程并发测试工具类

 欢迎大家评论区交流

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);
    }
}

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>