Java8 跑分代码 import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class Benchmark { //初始化得分 static int singleThreadScore = 0; static int multiThreadScore = 0; //无限循环跑分开关 st
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Benchmark { //初始化得分 static int singleThreadScore = 0; static int multiThreadScore = 0; //无限循环跑分开关 static boolean isContinue = true; public static void main(String[] args) throws InterruptedException { //去处理器逻辑核心数量 int CPUs = Runtime.getRuntime().availableProcessors(); System.out.println("逻辑处理器个数:" + CPUs); //创建单线程线程池 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(); //创建多线程线程池(大小为逻辑核心数2倍) ExecutorService fixedThreadPool = Executors.newFixedThreadPool(CPUs * 2); System.out.println("正在进行单线程测试 ... ..."); //进行单线程跑分 singleThreadExecutor.execute(() -> doBenchmark(false)); //跑5秒钟之后 循环开关设置为关闭 线程完成后 关闭线程池 Thread.sleep(5000); isContinue = false; singleThreadExecutor.shutdown(); Thread.sleep(1000); System.out.println("单线程得分:" + singleThreadScore); //打开循环开关 isContinue = true; System.out.println("正在进行多线程测试 ... ..."); //根据逻辑核心数的2倍创建多线程跑分 for (int threads = 0; threads < CPUs * 2; threads++) { fixedThreadPool.execute(() -> doBenchmark(true)); } //跑5秒钟之后 循环开关设置为关闭 线程完成后 关闭线程池 Thread.sleep(5000); isContinue = false; fixedThreadPool.shutdown(); Thread.sleep(1000); System.out.println("多线程得分:" + multiThreadScore); } static void doBenchmark(boolean isMultiThread) { int score = 0; //判断循环开关 无限循环跑分 for (; isContinue; ) { //创建1000长度的数组 int[] array = new int[1000]; int insideInt = 100000; for (int i = 0; i < array.length; i++) { //数据从100000递减 添加至数组中 array[i] = insideInt - i * 3; } bubble_sort(array); score++; } if (isMultiThread) { multiThreadScore += score; } else { singleThreadScore += score; } } //冒泡排序 static void bubble_sort(int[] unsorted) { for (int i = 0; i < unsorted.length; i++) { for (int j = i; j < unsorted.length; j++) { if (unsorted[i] > unsorted[j]) { int temp = unsorted[i]; unsorted[i] = unsorted[j]; unsorted[j] = temp; } } } } }