如果我是 24 届的就好了,说不定毕设能用上使用了虚拟线程的 Spring Boot。
由于我的 idea 2022.3 不支持 Java21,用不了 profiler,就用任务管理器将就看一看内存占用吧。
码
废话少说,上代码。虚拟线程和平台线程各 5w,平台线程池也是 5w,虚拟线程不需要线程池。每个线程睡 10 秒。
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.*;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) throws InterruptedException {
LocalDateTime start = LocalDateTime.now();
System.out.println(start);
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 50000).forEach(i -> executor.execute(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException ignored) {
}
}));
}
LocalDateTime now1 = LocalDateTime.now();
System.out.println(now1);
System.out.println(Duration.between(start, now1));
try (ScheduledExecutorService executor = Executors.newScheduledThreadPool(50000)) {
IntStream.range(0, 50000).forEach(i -> executor.execute(() -> {
try {
Thread.sleep(10000);
} catch (InterruptedException ignored) {
}
}));
}
LocalDateTime now2 = LocalDateTime.now();
System.out.println(now2);
System.out.println(Duration.between(now1, now2));
}
}
结论
虚拟线程总用时是 10.339s,内存占用最高到 280MB。
平台线程总用时是 44.811s,内存占用最高到 3.5 GB。
这差距,虚拟线程是真的牛。
2023-10-05