jd19支持虚拟线程,虚拟线程是轻量级的线程,它们不与操作系统线程绑定,而是由 JVM 来管理。它们适用于“每个请求一个线程”的编程风格,同时没有操作系统线程的限制。我们能够创建数以百万计的虚拟线程而不会影响吞吐。
做个 springboot demo 尝试一下。
环境
- jdk19
- gradle 7.6.1
- IntelliJ IDEA 2022.2.4
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.0.3'
id 'io.spring.dependency-management' version '1.1.0'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '19'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
tasks.named('test') {
useJUnitPlatform()
}
tasks.withType(JavaCompile) {
options.compilerArgs += "--enable-preview"
}
多线程demo
写一段多线程调用的代码,程序入口
package com.example.myvirtualthreaddemo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.support.TaskExecutorAdapter;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.Executors;
@EnableAsync
@SpringBootApplication
public class MyVirtualThreadDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyVirtualThreadDemoApplication.class, args);
}
@Bean
CommandLineRunner commandLineRunner(AsyncService asyncService){
return args -> {
for(int i = 0; i < 100; i++){
asyncService.fun(i);
}
};
}
}
package com.example.myvirtualthreaddemo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class AsyncService {
@Async
public void fun(int i) {
log.info("fun:{}", i);
}
}
运行结果,使用平台线程(默认8个)
使用虚拟线程
在MyVirtualThreadDemoApplication添加以下代码块
@Bean(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME)
public AsyncTaskExecutor asyncTaskExecutor(){
return new TaskExecutorAdapter(Executors.newVirtualThreadPerTaskExecutor());
}
运行结果,使用虚拟线程
遇到的一些问题
请使用 --enable-preview 以启用预览 API
解决办法:
- build.gradle里添加以下配置:
tasks.withType(JavaCompile) {
options.compilerArgs += "--enable-preview"
}
- 设置vm选项如图