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

相关推荐
jason成都1 小时前
RTKLIB Java 移植踩坑复盘:卡尔曼滤波核心逻辑修复与滑坡场景实测验证
java·开发语言
一次旅行2 小时前
【AI工具】Rust-Based CLI:用 xargs 和并行加速你的 Linux 日常
linux·开发语言·rust
老毛肚2 小时前
juc线程通信
java·开发语言·jvm
跨境数据猎手3 小时前
反向海淘实战|独立站搭建+国内电商API对接
开发语言·爬虫·架构
花颜yyds3 小时前
Java 开发基础速查手册
java
没钥匙的锁13 小时前
05-Java面向对象构造器与封装
java·开发语言
仙人球部落3 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
2401_894915533 小时前
Geo搜索优化排名源码部署搭建全流程详解
android·开发语言·flask·php·精选
aaPIXa6224 小时前
C++采样引导优化SPGO——比PGO更智能的编译器决策新方案
java·c++·人工智能