Java:Java多线程实现性能测试

2021-01-07 22:28

阅读:519

标签:tail   关闭   runnable   fixed   port   net   mem   await   for   

创建多线程和线程池

 

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 ) {
    //执行线程
    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) + "次/秒");

 

 

具体逻辑

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

 

Java:Java多线程实现性能测试

标签:tail   关闭   runnable   fixed   port   net   mem   await   for   

原文地址:https://www.cnblogs.com/nhdlb/p/12968935.html


评论


亲,登录后才可以留言!