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耗时也是差不多。可见虚拟线程是轻量级的,占资源少。

相关推荐
爱码小白19 分钟前
importlib模块
开发语言·前端·python
令狐前生34 分钟前
Intellij IDEA 2025 破解安装
java·ide·intellij-idea
数聚天成DeepSData1 小时前
数聚天成 DeepSData 数据价值落地实战指南
java·maven·devops
techdashen1 小时前
Go设计取舍之四: map不变时能否并发修改不同value
开发语言·后端·golang
小小小米粒1 小时前
阿姆达尔定律(Amdahl‘s Law)
java·开发语言
知彼解己1 小时前
Java 版本演进
java·开发语言·spring boot
风样滴男人哟1 小时前
PHP特性之反射类ReflectionClass机制
android·开发语言·php
极客先躯1 小时前
高级java每日一道面试题-2026年05月11日-实战篇[Docker]-如何容器化金融产品推荐系统?
java·运维·docker·容器·金融·高级面试·金融产品推荐系统
看昭奚恤哭1 小时前
Flutter 布局核心思想
开发语言·javascript·flutter
朱容zr3331332 小时前
为什么推荐使用自增主键?使用UUID作为主键的优缺点是什么?
java·运维·数据库·后端·mysql·面试·性能优化