Java虚拟线程(一)
2023下半年,Java 21开始正式支持虚拟线程 Virtual Thread
本文先介绍几种使用方法。
1. 直接创建虚拟线程并运行
Thread vt = Thread.startVirtualThread(new Runnable() {
@Override
public void run() {
System.out.println("hello virtual thread 1");
}
});
2. 创建虚拟线程但不运行,之后手动运行
vt = Thread.ofVirtual().unstarted(() -> {
System.out.println("hello virtual thread 2");
});
vt.start();
3. 通过虚拟线程ThreadFactory创建
ThreadFactory threadFactory = Thread.ofVirtual().name("my-virtual-thread-").factory();
vt = threadFactory.newThread(() -> {
System.out.println("hello virtual thread 3");
});
vt.start();
4. 使用Executors.newVirtualThreadPerTaskExecutor ExecutorService创建虚拟线程
ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
executorService.submit(() -> {
System.out.println("hello virtual thread 4");
});
5. 用普通的Executors.newThreadPerTaskExecutor ExecutorService、配合虚拟线程工厂,创建虚拟线程
executorService = Executors.newThreadPerTaskExecutor(threadFactory);
executorService.submit(() -> {
System.out.println("hello virtual thread 5");
});
虚拟线程的世界没有线程池
上面4、5的例子虽然用Executors创建了ExecutorService,但跟之前直觉不一样,严格说并不是创建了两个线程池。这俩都属于“one Thread Per Task”的。
虚拟线程非常轻量,创建的开销很小,不需要池化进行复用,用的时候直接创建,然后等GC回收就行了,非常暴力!
但线程池的作用不只是复用线程,也有隔离和限制并发的作用,在虚拟线程的情况下,这个通常可以用信号量Semaphore来解决,下一篇我们介绍。
完整演示代码
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class VThreadTest {
public static void main(String[] args) throws InterruptedException {
//1. 直接创建虚拟线程并运行
Thread vt = Thread.startVirtualThread(new Runnable() {
@Override
public void run() {
System.out.println("hello virtual thread 1");
}
});
TimeUnit.SECONDS.sleep(1);
//2. 创建虚拟线程但不运行,之后手动运行
vt = Thread.ofVirtual().unstarted(() -> {
System.out.println("hello virtual thread 2");
});
vt.start();
TimeUnit.SECONDS.sleep(1);
//3. 通过虚拟线程ThreadFactory创建
ThreadFactory threadFactory = Thread.ofVirtual().name("my-virtual-thread-").factory();
vt = threadFactory.newThread(() -> {
System.out.println("hello virtual thread 3");
});
vt.start();
TimeUnit.SECONDS.sleep(1);
//4. 使用newVirtualThreadPerTaskExecutor ExecutorService创建虚拟线程
ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();
executorService.submit(() -> {
System.out.println("hello virtual thread 4");
});
TimeUnit.SECONDS.sleep(1);
//5. 用普通的newThreadPerTaskExecutor ExecutorService、配合虚拟线程工厂,创建虚拟线程
executorService = Executors.newThreadPerTaskExecutor(threadFactory);
executorService.submit(() -> {
System.out.println("hello virtual thread 5");
});
TimeUnit.SECONDS.sleep(1);
}
}
运行结果:
hello virtual thread 1
hello virtual thread 2
hello virtual thread 3
hello virtual thread 4
hello virtual thread 5
浙公网安备 33010602011771号