Java多线程实现性能测试

 

1、创建多线程和线程池的代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
int threadSize = 100;  //开启的线程数
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(threadSize);
long start = System.currentTimeMillis();
//让线程池中的每一个线程都开始工作
for (int j = 0; j < threadSize; j++) {
    //执行线程
    executorService.execute(new TestPerformance(threadSize));
}
//等线程全部执行完后关闭线程池
executorService.shutdown();
executorService.awaitTermination(Integer.MAX_VALUE, TimeUnit.DAYS);
long end = System.currentTimeMillis();
System.out.println("测试次数:" + TestPerformance.atomicInteger.get());
System.out.println("用时:" + (end - start));
System.out.println("速度:" + TestPerformance.atomicInteger.get() * 1000 / (end - start) + "次/秒");

 

2、具体要测试性能的代码:

 

package com.test.performance;
 
 
import java.util.concurrent.atomic.AtomicInteger;
 
/**
 * 测试性能.
 */
public class TestPerformance implements Runnable {
 
    //每个线程的执行次数
    private int size;
 
    //记录多线程的总执行次数,保证高并发下的原子性
    public static AtomicInteger atomicInteger = new AtomicInteger(0);
 
    public TestPerformance(int size) {
        this.size = size;
    }
 
    @Override
    public void run() {
 
        int count = 0;
        while (count < size) {
            count++;
 
            atomicInteger.getAndIncrement();
 
            ///
        //在此写入需要测试性能的代码块
        ///
 
            System.out.println("线程ID与对应的执行次数:" + Thread.currentThread().getId() + "--->" + count);
        }
    }
}

 

 

 

转: https://blog.csdn.net/weixin_43192102/article/details/106195948

 

posted @ 2020-11-03 14:58  与f  阅读(837)  评论(0编辑  收藏  举报