Java虚拟线程实战:Project Loom让并发编程更简单

Java虚拟线程实战:Project Loom让并发编程更简单
一、虚拟线程 vs 平台线程平台线程对应操作系统线程创建成本高约1MB栈内存数量受限虚拟线程JVM 管理的轻量级线程创建成本极低约几KB可创建数百万个// 平台线程创建100万个会OOM Thread platformThread new Thread(() - doWork()); platformThread.start(); // 虚拟线程创建100万个轻松搞定 Thread virtualThread Thread.ofVirtual().start(() - doWork());回到顶部二、创建虚拟线程的四种方式// 方式1Thread.ofVirtual() Thread vt1 Thread.ofVirtual().name(vt-1).start(() - { System.out.println(Virtual thread: Thread.currentThread()); }); // 方式2Thread.startVirtualThread() Thread vt2 Thread.startVirtualThread(() - { System.out.println(Running in virtual thread); }); // 方式3虚拟线程 ExecutorService try (ExecutorService executor Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() - processRequest()); executor.submit(() - processRequest()); } // 方式4ThreadFactory ThreadFactory factory Thread.ofVirtual().factory(); Thread vt4 factory.newThread(() - doWork()); vt4.start();回到顶部三、实战高并发 HTTP 请求处理// 传统方式线程池受限于线程数 ExecutorService threadPool Executors.newFixedThreadPool(200); // 虚拟线程方式每个请求一个虚拟线程 RestController public class UserController { GetMapping(/users/{id}) public User getUser(PathVariable Long id) { // 虚拟线程会在 I/O 阻塞时自动挂起释放载体线程 return userService.findById(id); // 数据库查询 } } // Spring Boot 3.2 开启虚拟线程 // application.yml // spring: // threads: // virtual: // enabled: true回到顶部四、性能对比测试public class PerformanceTest { // 模拟 I/O 密集型任务 static void ioTask() throws InterruptedException { Thread.sleep(100); // 模拟数据库查询 } public static void main(String[] args) throws Exception { int taskCount 10_000; // 平台线程池 long start1 System.currentTimeMillis(); try (ExecutorService pool Executors.newFixedThreadPool(200)) { ListFuture? futures new ArrayList(); for (int i 0; i taskCount; i) { futures.add(pool.submit(() - { ioTask(); return null; })); } for (Future? f : futures) f.get(); } System.out.println(Platform threads: (System.currentTimeMillis() - start1) ms); // 输出约5200ms // 虚拟线程 long start2 System.currentTimeMillis(); try (ExecutorService vExecutor Executors.newVirtualThreadPerTaskExecutor()) { ListFuture? futures new ArrayList(); for (int i 0; i taskCount; i) { futures.add(vExecutor.submit(() - { ioTask(); return null; })); } for (Future? f : futures) f.get(); } System.out.println(Virtual threads: (System.currentTimeMillis() - start2) ms); // 输出约120ms提升40倍 } }回到顶部五、注意事项避免 synchronized 块会导致虚拟线程固定pinning改用 ReentrantLock不适合 CPU 密集型任务虚拟线程优势在 I/O 密集型场景ThreadLocal 谨慎使用大量虚拟线程时内存占用可能增加// 错误synchronized 导致 pinning synchronized (lock) { Thread.sleep(100); // 虚拟线程被固定无法挂起 } // 正确使用 ReentrantLock ReentrantLock lock new ReentrantLock(); lock.lock(); try { Thread.sleep(100); // 虚拟线程可以正常挂起 } finally { lock.unlock(); }回到顶部总结虚拟线程是 Java 并发编程的重大突破特别适合 I/O 密集型的微服务场景。