我正在尝试用Java测试虚拟线程引用loom项目,我使用的是以下JDK 19 loom版本:
package com;
import java.util.concurrent.ThreadFactory;
public class a {
public static void main (String [] args) throws Exception{
Runnable printThread = () -> System.out.println(Thread.currentThread());
ThreadFactory virtualThreadFactory = Thread.builder().virtual().factory();
ThreadFactory kernelThreadFactory = Thread.builder().factory();
Thread virtualThread = virtualThreadFactory.newThread(printThread);
Thread kernelThread = kernelThreadFactory.newThread(printThread);
virtualThread.start();
kernelThread.start();
}
}
我有以下IntelliJ配置:
但我有以下错误:
并且似乎没有确定线程的构建者
我想知道我还需要什么?
您正在使用过时的示例。
在织机的当前状态下,您的示例必须看起来像
public static void main(String[] args) throws InterruptedException {
Runnable printThread = () -> System.out.println(Thread.currentThread());
ThreadFactory virtualThreadFactory = Thread.ofVirtual().factory();
ThreadFactory kernelThreadFactory = Thread.ofPlatform().factory();
Thread virtualThread = virtualThreadFactory.newThread(printThread);
Thread kernelThread = kernelThreadFactory.newThread(printThread);
virtualThread.start();
kernelThread.start();
virtualThread.join();
kernelThread.join();
}
但您也可以使用简化的
public static void main(String[] args) throws InterruptedException {
Runnable printThread = () -> System.out.println(Thread.currentThread());
Thread virtualThread = Thread.startVirtualThread(printThread);
Thread kernelThread = Thread.ofPlatform().start(printThread);
virtualThread.join();
kernelThread.join();
}
请记住,这是半成品,文件可能会很快过时。