創建多線程和線程池
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) + "次/秒");
具體邏輯
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