多线程并发测试工具类

 欢迎大家评论区交流

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  threads = new HashSet<>(threadSize);
            //批量新建线程
            for (int i = 0; i {
                            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);
    }
}

你可能感兴趣的:(测试工具,java,多线程,并发)