多线程测试类

时间:2019-08-24
本文章向大家介绍多线程测试类,主要包括多线程测试类使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
package base_class;

import java.util.concurrent.CountDownLatch;

/**
 * 多线程测试器
 */
public class ManyThreadStarter {

    private int count;

    public ManyThreadStarter(){
        count = 10000;
    }

    public ManyThreadStarter(int count){
        this.count = count;
    }

    public void allThreadRun(Run run){
        CountDownLatch latch = new CountDownLatch(count);

        long start = System.currentTimeMillis();
        for(int i=0;i<count;i++){
            new Thread(()->{
                try{
                    run.run();
                }catch (Exception e) {
                  e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }).start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行耗时:"+(System.currentTimeMillis()-start)+"毫秒");

    }

    public interface Run{
        void run();
    }

}

原文地址:https://www.cnblogs.com/math-and-it/p/11404463.html