gpt4 book ai didi

java - 尝试将 Project Loom/Virtual Threads 与 OpenJDK 19-loom JAVA 结合使用时出现问题

转载 作者:行者123 更新时间:2023-12-01 23:05:43 24 4
gpt4 key购买 nike

我正在尝试在 Java 中测试虚拟线程引用 loom 项目,并且我正在使用以下 JDK 19-loom 版本:

enter image description here

  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 配置:

enter image description here

但是我有以下错误:

enter image description here

而且线程的构建者好像没有被识别

enter image description here

我想知道我还需要什么?

最佳答案

您使用的是过时的示例。

在 Loom 的当前状态下,您的示例必须看起来像

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();
}

请记住,这是一项正在进行的工作,文档很快就会过时。

关于java - 尝试将 Project Loom/Virtual Threads 与 OpenJDK 19-loom JAVA 结合使用时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70932952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com