package org.xxkk.utils.util;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author xxkk
* @version 1.0.0
* @title ThreadTest
* @description ʕ•ᴥ•ʔ
* @create 2024/7/27 22:55
**/
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
long begin = System.currentTimeMillis();
ThreadTest test = new ThreadTest();
// test.task1_test();
// test.task2_test();
test.task3_test();
long end = System.currentTimeMillis();
long spend_t = (end - begin) / 1000;
System.out.println("总耗时:" + spend_t);
}
private void task1_test() {
List<Runnable> task = new LinkedList<>();
int tn = 10000000;
for (int i = 0; i < tn; i++) {
if (i % 100000 == 0)
System.out.println("Remaining:" + (tn - i));
task.add(new Runnable() {
@Override
public void run() {
JsonUtils.toJsonObj("{\"obj\":1}");
}
});
}
ExecutorService es = Executors.newFixedThreadPool(2);
task.forEach(es::execute);
es.shutdown();
while (!es.isTerminated()) {
}
}
private void task2_test() {
ExecutorService es = Executors.newFixedThreadPool(2);
int tn = 10000000;
for (int i = 0; i < tn; i++) {
if (i % 100000 == 0)
System.out.println("Remaining:" + (tn - i));
es.execute(new Runnable() {
@Override
public void run() {
try {
JsonUtils.toJsonObj("{\"obj\":1}");
} catch (Exception e) {
}
}
});
}
es.shutdown();
while (es.isTerminated()){}
}
private void task3_test() throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(2);
int tn = 10000000;
CountDownLatch latch = new CountDownLatch(tn);
for (int i = 0; i < tn; i++) {
if (i % 100000 == 0)
System.out.println("Remaining:" + (tn - i));
es.execute(new Runnable() {
@Override
public void run() {
try {
JsonUtils.toJsonObj("{\"obj\":1}");
} catch (Exception e) {
}finally {
latch.countDown();
}
}
});
}
es.shutdown();
latch.await();
}
}
分别执行任务1、2、3耗时分别为12、15、19
任务1cpu图
任务2cpu图
本人不知为何for循环内创建并执行多线程和for循环内创建任务线程并在循环外一并提交会出现cpu图谱的如此差异?