| 知乎专栏 |
package cn.netkiller.thread;
import static java.lang.Thread.*;
public class VirtualThreadsTest {
public static void main(String[] args) throws InterruptedException {
var virtualThread = startVirtualThread(() -> System.out.println("Hello from the virtual thread"));
virtualThread.join();
}
}
运行演示
neo@MacBook-Pro-M2 thread % java --source 20 --enable-preview VirtualThreadsTest.java 注: VirtualThreadsTest.java 使用 Java SE 20 的预览功能。 注: 有关详细信息,请使用 -Xlint:preview 重新编译。 Hello from the virtual thread
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 10000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1));
return i;
});
});
}
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VirtualThreadExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
executor.submit(() -> {
System.out.println(Thread.currentThread().getName())
});
executor.shutdown();
}
}
Thread.ofVirtual().start(Runnable); Thread.ofVirtual().unstarted(Runnable);
Thread.ofVirtual().start(Runnable); Thread.ofVirtual().unstarted(Runnable);
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
Future<User> user = executor.submit(() -> userService.getUser(id));
Future<Order> order = executor.submit(() -> orderService.getOrder(id));
return new Result(user.get(), order.get());
}
package cn.netkiller.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class Test {
static void main(String[] args) {
// 1. 创建虚拟线程执行器
ExecutorService virtualThreadExecutor = Executors.newVirtualThreadPerTaskExecutor();
// 2. 设置并发上限(比如限制同时执行 10 个任务)
Semaphore semaphore = new Semaphore(10);
// 3. 提交任务时通过信号量管控并发
for (int i = 0; i < 1000; i++) {
int taskId = i;
try {
// 获取许可:若已达10个并发,此处阻塞
semaphore.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
virtualThreadExecutor.submit(() -> {
try {
// 业务逻辑:执行具体任务
System.out.println("执行任务 " + taskId + ",虚拟线程:" + Thread.currentThread());
Thread.sleep(5000); // 模拟任务耗时
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
} finally {
// 释放许可:任务完成后归还,允许新任务执行
semaphore.release();
}
});
}
// 4. 关闭执行器(按需)
virtualThreadExecutor.shutdown();
}
}