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);
}
}
}