LWJGL Error: GLFW may only be used on the main thread. This check may be disabled with Configuration.GLFW_CHECK_THREAD0

LWJGL Error: GLFW may only be used on the main thread. This check may be disabled with Configuration.GLFW_CHECK_THREAD0

我正在尝试使用 LWJGL 创建一个 window,它只有一个线程 game。当我尝试 运行 我的代码时,出现错误:GLFW may only be used on the main thread. This check may be disabled with Configuration.GLFW_CHECK_THREAD0.。起初,它建议添加一个 JVM 参数 -XstartOnFirstThread,我将我的 IDE 配置为这样做,但现在它建议:This check may be disabled with Configuration.GLFW_CHECK_THREAD0.。我该如何实施或以其他方式修复它?

Main.java:

package main;

import engine.io.Window;

public class Main implements Runnable {
    public Thread game;
    
    public static Window window;
    
    public static final int WIDTH = 1280, HEIGHT = 760;
    
    public void start() {
        game = new Thread(this, "game");
        game.start();
    }
    
    public static void init() {
        System.out.println("Initializing game!");
        window = new Window(WIDTH, HEIGHT, "game");
        
        window.create();
    }
    
    public void run() {
        init();
        while (true) {
            update();
            render();
        }
    }
    
    private void update() {
        System.out.println("Updating game");
    }
    
    private void render() {
        System.out.println("Rendering game");
    }
    
    public static void main(String[] args) {
        new Main().start();
    }
}

Window.java:

package engine.io;

import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWVidMode;

public class Window {
    private int width, height;
    private String title;
    private long window;
    
    public Window(int width, int height, String title) {
        this.width = width;
        this.height = height;
        this.title = title;
    }
    
    public void create() {
        if (!GLFW.glfwInit()) {
            System.err.println("ERROR: GLFW wasn't initialized");
            return;
        }
        
        window = GLFW.glfwCreateWindow(width, height, title, 0, 0);
        
        if (window == 0) {
            System.err.println("ERROR: Window wasn't created");
            return;
        }
        
        GLFWVidMode videoMode = GLFW.glfwGetVideoMode(GLFW.glfwGetPrimaryMonitor());
        GLFW.glfwSetWindowPos(window, (videoMode.width() - width)/2, (videoMode.height() - height)/2);
        GLFW.glfwShowWindow(window);
    }
}

您正在从单独生成的线程调用 GLFW methods/functions。这在 macOS 上不可能。 请参阅 GLFW 自己的文档,例如对于 glfwCreateWindow,在“线程安全”部分下:

Thread safety

This function must only be called from the main thread.

大多数其他函数也是如此,例如 glfwInitglfwShowWindowglfwPollEvents/glfwWaitEvents 等。请参阅 GLFW 的文档。

因此,大多数 GLFW 函数 必须 main 线程调用,该线程是由 JVM 进程隐式创建的,最初调用您的主要方法。

目前,您程序中的主线程所做的唯一事情就是生成一个新线程,然后它处于休眠状态,直到 JVM 退出。这是完全没有必要的。您也可以使用主线程来完成这项工作。

为了解决这个问题,只需不要 spawn/create一个单独的线程。