1. 程式人生 > 實用技巧 >Java多執行緒實現效能測試

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