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

相关推荐
软件技术NINI8 分钟前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
会编程的吕洞宾1 小时前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring
山楂树の2 小时前
Python Pandas 数据处理:数据读取、筛选、清洗、排序与分组
开发语言·python·pandas
Rain的Java大神之路2 小时前
Spring Boot 4 + Spring AI 2.0 迁移实战:别急着改版本号,先算算你欠了多少债
java·后端·ai编程
代码不停3 小时前
Linux基础知识
java·linux·数据库
xurileidian3 小时前
第 22 篇 · 边玩边学Python · 双等号与 is 不是一回事
开发语言·python·spring
钉先生贾3 小时前
HarmonyOS 7.0 性能排障实战 43:图片与大资源加载抖动时,怎样区分解码、布局与状态更新
java·前端·harmonyos
FRing033 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
syf0611133 小时前
Java Math 类详解:常用数学运算方法全解析
java·开发语言
是main不是漫4 小时前
【双指针 | LeetCode11 盛最多水的容器】O(n²) 超时,O(n) 封神:这道“装水题“只差一个思路
开发语言·数据结构·c++·算法