🔍 什么是 Virtual Threads?
Virtual Threads 是一种由 JVM 调度的用户态线程,也称为协程(coroutine)。它与操作系统的内核线程不是一一对应的,而是由 JVM 在少量平台线程(Platform Threads)上进行多路复用。
🛠️ 步骤一:最简单的虚拟线程示例
public class VirtualThreadDemo {
public static void main(String[] args) throws InterruptedException {
Thread virtualThread = Thread.ofVirtual()
.name("VT-")
.unstarted(() -> {
System.out.println("当前线程: " + Thread.currentThread());
});
virtualThread.start();
virtualThread.join(); // 等待完成
}
}
输出:
当前线程: VirtualThread[#21][task, host:/1]
📌 使用 Thread.ofVirtual()
创建虚拟线程,语法简洁、语义清晰。
🧪 步骤二:批量启动虚拟线程测试并发能力
public class ManyVirtualThreads {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10_000; i++) {
final int taskId = i;
Thread.ofVirtual().start(() -> {
System.out.println("任务 " + taskId + " 正在执行");
});
}
Thread.sleep(2000); // 等待所有任务执行完毕
}
}
📌 可轻松创建数万个并发任务,而不会出现 OOM 错误或明显性能下降。
🧩 步骤三:在 Spring Boot 中使用虚拟线程提升 QPS
以 Spring Boot 3.1+ 为例,启用虚拟线程非常简单。
1. 修改配置文件 application.properties
spring.threads.virtual.enabled=true
2. 编写一个耗时的 Controller 方法
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() throws InterruptedException {
Thread.sleep(1000); // 模拟慢请求
return "Hello from Virtual Thread!";
}
}
📌 启用后,每个请求都会在一个虚拟线程中处理,极大提升并发能力。
🧨 步骤四:对比虚拟线程 vs 固定线程池性能
编写一个压力测试类:
public class PerformanceComparison {
private static final ExecutorService fixedPool = Executors.newFixedThreadPool(100);
private static final ExecutorService virtualPool = Executors.newVirtualThreadPerTaskExecutor();
public static void testPerformance(ExecutorService executor) throws Exception {
List<Future<?>> futures = new ArrayList<>();
long start = System.currentTimeMillis();
for (int i = 0; i < 10_000; i++) {
futures.add(executor.submit(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {}
}));
}
for (var f : futures) f.get();
long end = System.currentTimeMillis();
System.out.printf("总耗时: %d ms%n", end - start);
}
public static void main(String[] args) throws Exception {
System.out.println("固定线程池测试:");
testPerformance(fixedPool);
System.out.println("虚拟线程池测试:");
testPerformance(virtualPool);
}
}
📌 实验结果表明,虚拟线程在 IO 密集型任务中,性能远超传统线程池。