在IntelliJ中使用Java 19运行虚拟线程程序时遇到异常
解决Java 19虚拟线程预览API报错问题
问题概述
在IntelliJ中配置Java 19运行虚拟线程代码时,先后遇到两个错误:
- 初始使用IntelliJ 2021.3.3时报错:
java: invalid source release 18 with --enable-preview (preview language features are only supported for release 19)
- 升级到IntelliJ 2022.2.3后仍报错:
java: ofVirtual() is a preview API and is disabled by default. (use --enable-preview to enable preview APIs)
已做配置:
- 项目SDK设为Java 19
- pom.xml指定source和target版本为19
- 已在VM选项和编译器偏好中添加
--enable-preview
根本原因
Java 19的虚拟线程属于预览API,需要同时在编译阶段和运行阶段完整启用预览特性,仅单处配置会导致报错;此外旧版本IntelliJ对Java 19的语言级别识别存在缺陷。
完整解决步骤
1. 确保IDE版本适配
Java 19发布于2022年9月,必须使用IntelliJ 2022.2及以上版本才能完美支持,已升级到2022.2.3可跳过此步。
2. 完善Maven编译配置
仅设置source/target不够,需要在maven-compiler-plugin中明确启用预览特性,修改pom.xml:
<project> <!-- 保留原有配置 --> <properties> <maven.compiler.source>19</maven.compiler.source> <maven.compiler.target>19</maven.compiler.target> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <compilerArgs> <arg>--enable-preview</arg> </compilerArgs> </configuration> </plugin> </plugins> </build> </project>
3. 配置IntelliJ编译器预览参数
- 打开
File > Settings > Build, Execution, Deployment > Compiler > Java Compiler - 在
Override compiler parameters per-module中找到目标项目模块,将--enable-preview添加到Additional command line parameters - 确认
Project bytecode version设置为19
4. 配置运行时VM选项
- 点击右上角运行按钮旁的下拉菜单,选择
Edit Configurations - 找到对应运行配置,在
VM options中添加--enable-preview - 确认
JRE选择的是Java 19版本
5. 验证项目语言级别
- 打开
File > Project Structure > Project Settings > Project - 确保
Project SDK为19,Project language level选择19 (Preview) - Virtual Threads
测试代码验证
运行虚拟线程代码时,建议给主线程加短暂休眠(虚拟线程为守护线程,主线程结束会直接终止程序):
public class VTSimple { public static void main(String[] args) { Runnable runnable = () -> System.out.println("Inside Runnable"); Thread.startVirtualThread(runnable); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } }
内容的提问来源于stack exchange,提问作者SRJ
相关产品推荐
相关产品推荐

