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

相关推荐
wangchunyu1144 小时前
JAVA AQS与Lock实现原理(含CAS)
java·开发语言·word
爱喝水的鱼丶5 小时前
SAP-ABAP:ECC→S/4HANA ABAP 迁移升级指南——程序改造、语法兼容与性能优化 导语
运维·开发语言·性能优化·sap·abap·经验交流·开发交流
w_zero_one5 小时前
算法--模拟
java·数据结构·算法
小灰灰搞电子5 小时前
Rust+Slint 实现FTP客户端调试助手源码分享
开发语言·后端·rust
外收内放5 小时前
面向对象高级(实战案例)
开发语言·python·学习
Javatutouhouduan5 小时前
阿里1658页Java面试题总结(含答案)
java·高并发·java面试·java面试题·后端开发·java程序员·java八股文
秋天的怀念_David5 小时前
算法一千零一夜 · 第十三夜 幻方,武侠世界里的数学迷宫
java·程序人生·算法
专业程序开发源6 小时前
springboot欧缇蔓月子中心管理系统82697-计算机课程设计、毕业设计
java·spring boot·后端·python·spring·django·课程设计
秋天的怀念_David6 小时前
算法一千零一夜 · 第十四夜 幻方与奇妙的二进制
java·程序人生·算法
thefool1122666 小时前
网络编程^
java