惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
B
Blog RSS Feed
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Google DeepMind News
Google DeepMind News
D
Docker
Blog — PlanetScale
Blog — PlanetScale
M
MIT News - Artificial intelligence
C
Check Point Blog
The Cloudflare Blog
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
量子位
The GitHub Blog
The GitHub Blog
Microsoft Azure Blog
Microsoft Azure Blog
I
InfoQ
T
The Blog of Author Tim Ferriss
博客园 - 【当耐特】
Vercel News
Vercel News
P
Proofpoint News Feed
Hugging Face - Blog
Hugging Face - Blog
V
V2EX
博客园 - 司徒正美

博客园 - 幽州散人

SQL优化案例 synchronized 为啥会让虚拟线程卸载失效 主线任务和使命 温州3日之旅 CompletableFuture + 异步Servlet:同步的姿势、异步的效果 Snowflake雪花算法与发号器的应用 windows Java 幽灵转发壳进程 也谈MySQL limit offset深翻页问题 SHOW SESSION STATUS 与 Handler 变量 MySQL 5.7 Profiles 执行性能分析 MySQL临时表与文件排序 MySQL 5.7 MRR多范围读优化 MySQL 5.7 ICP索引条件下推优化 MySQL符合索引与最左前缀原则 从I/O 的物理成本理解回表和索引覆盖 第4个电瓶以及补漆 Flink原理:并行度与keyGroup桶 什么是数字批发银行 Java虚拟线程(三)实现原理 Java虚拟线程(二) 大模型推理层服务化架构 传奇调查员之路:理智值-99,但我必须听懂深渊的语言 js里调用智能合约读/写函数的方法的区别 字节与其16进制字符表示转换的bug Redisson分布式锁 交易心得 DexScreener接口初探 某安全软件跑飞了。。 Ed25519算法签名与验签的Java实现 Tendermint拜占庭容错引擎
Java虚拟线程(一)
幽州散人 · 2026-06-11 · via 博客园 - 幽州散人

2023下半年,Java 21开始正式支持虚拟线程 Virtual Thread
本文先介绍几种使用方法。

1. 直接创建虚拟线程并运行

Thread vt = Thread.startVirtualThread(new Runnable() {
     @Override
     public void run() {
        System.out.println("hello virtual thread 1");
     }
});

2. 创建虚拟线程但不运行,之后手动运行

vt = Thread.ofVirtual().unstarted(() -> {
    System.out.println("hello virtual thread 2");
});
vt.start();

3. 通过虚拟线程ThreadFactory创建

ThreadFactory threadFactory = Thread.ofVirtual().name("my-virtual-thread-").factory();
vt = threadFactory.newThread(() -> {
     System.out.println("hello virtual thread 3");
});
vt.start();

4. 使用Executors.newVirtualThreadPerTaskExecutor ExecutorService创建虚拟线程

ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
executorService.submit(() -> {
     System.out.println("hello virtual thread 4");
});

5. 用普通的Executors.newThreadPerTaskExecutor ExecutorService、配合虚拟线程工厂,创建虚拟线程

executorService = Executors.newThreadPerTaskExecutor(threadFactory);
executorService.submit(() -> {
     System.out.println("hello virtual thread 5");
});

虚拟线程的世界没有线程池

上面4、5的例子虽然用Executors创建了ExecutorService,但跟之前直觉不一样,严格说并不是创建了两个线程池。这俩都属于“one Thread Per Task”的。
虚拟线程非常轻量,创建的开销很小,不需要池化进行复用,用的时候直接创建,然后等GC回收就行了,非常暴力!
但线程池的作用不只是复用线程,也有隔离和限制并发的作用,在虚拟线程的情况下,这个通常可以用信号量Semaphore来解决,下一篇我们介绍。

完整演示代码

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class VThreadTest {
    public static void main(String[] args) throws InterruptedException {
        //1. 直接创建虚拟线程并运行
        Thread vt = Thread.startVirtualThread(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello virtual thread 1");
            }
        });
        TimeUnit.SECONDS.sleep(1);

        //2. 创建虚拟线程但不运行,之后手动运行
        vt = Thread.ofVirtual().unstarted(() -> {
            System.out.println("hello virtual thread 2");
        });
        vt.start();
        TimeUnit.SECONDS.sleep(1);

        //3. 通过虚拟线程ThreadFactory创建
        ThreadFactory threadFactory = Thread.ofVirtual().name("my-virtual-thread-").factory();
        vt = threadFactory.newThread(() -> {
            System.out.println("hello virtual thread 3");
        });
        vt.start();
        TimeUnit.SECONDS.sleep(1);

        //4. 使用newVirtualThreadPerTaskExecutor ExecutorService创建虚拟线程
        ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
        executorService.submit(() -> {
            System.out.println("hello virtual thread 4");
        });
        TimeUnit.SECONDS.sleep(1);

        //5. 用普通的newThreadPerTaskExecutor ExecutorService、配合虚拟线程工厂,创建虚拟线程
        executorService = Executors.newThreadPerTaskExecutor(threadFactory);
        executorService.submit(() -> {
            System.out.println("hello virtual thread 5");
        });
        TimeUnit.SECONDS.sleep(1);

    }
}

运行结果:

hello virtual thread 1
hello virtual thread 2
hello virtual thread 3
hello virtual thread 4
hello virtual thread 5