java 虚拟线程

听说Java有虚拟线程,可以高并发执行任务。测试下虚拟线程。

java 复制代码
public static void test() {
        // 静态工厂
        Thread thread = Thread.ofVirtual()
                .name("myVirtualThread")
                .start(() ->
                {
                    System.out.println("这铮铮之音,如惊涛拍岸,风卷残云,指端似有雄兵百万!");
                    System.out.println("如山涧小溪,清澈见底。非心旷神怡者不能为之");
                    System.out.println("心乱则音燥,心静则音纯;心慌则音误,心泰则音清。听诸葛亮弹琴,如观其肺腑也!我能为诸葛亮知音,不胜荣幸!");
                    System.out.println("threadID: " + Thread.currentThread().getId()
                            + ", threadName:" + Thread.currentThread().getName());
                }
        );
        try {
            thread.join();// 等着虚拟线程跑完
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 虚拟线程池
        ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
        Future<?> future = executor.submit(() -> {
            System.out.println("龙能大能小,能升能隐;大则兴云吐雾,小则隐介藏形;升则飞腾于宇宙之间,隐则潜伏于波涛之内。方今春深,龙乘时变化,犹人得志而纵横四海。龙之为物,可比世之英雄。玄德久历四方,必知当世英雄,请试指言之。");
        });
        try {
            future.get();// 等着虚拟线程跑完
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

运行:

ok. 看上去和普通线程没啥区别。

再测试下,并发:

java 复制代码
public static void test2() {
        int taskCount = 100;    // 同时启动 100 个任务
        int sleepSeconds = 1;    // 每个任务阻塞 1 秒

        // -------- 虚拟线程 --------
        Instant start = Instant.now();
        AtomicInteger finished = new AtomicInteger(0);

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            for (int i = 0; i < taskCount; i++) {
                Future<?> future = executor.submit(() -> {
                    try {
                        Thread.sleep(sleepSeconds * 1000);   // 阻塞1秒。 挂起,不影响其他任务并发执行。
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    finished.incrementAndGet();
                });
            }
        } // try-with-resources 会自动调用 executor.close(),等待所有任务完成。

        Duration elapsed = Duration.between(start, Instant.now());
        System.out.printf("虚拟线程: %d 个任务, 每个阻塞 %d 秒, 总耗时 %d 毫秒, 完成数 %d%n",
                taskCount, sleepSeconds, elapsed.toMillis(), finished.get());
    }

运行:

ok. 把任务数改成1000耗时也是差不多。可见虚拟线程是轻量级的,占资源少。

相关推荐
weixin_440730505 分钟前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
sugarzhangnotes30 分钟前
【无标题】
开发语言·人工智能·python
geovindu33 分钟前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
用户1305180712151 小时前
JDBC学习DAY2:从Statement到PreparedStatement
java
蛋蛋的就会顺顺的2 小时前
hot100——矩阵
java·数据结构·算法·leetcode·力扣
周杰偷奶茶2 小时前
【Java】数组的定义和使用(附管理系统实战案例)
java·开发语言
橙子圆1232 小时前
JUC之集合类不安全
java·开发语言
阿里嘎多学长3 小时前
2026-09-29 GitHub 热点项目精选
开发语言·程序员·github·代码托管
Bruce_Liuxiaowei3 小时前
网页版 DeepSeek “harness desktop“ WebGL 上下文创建失败排查实录
开发语言·javascript·webgl
狗凯之家源码网3 小时前
PHP 用户反馈系统源码深度评测与实战指南
开发语言·php·用户反馈系统