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