gpt4 book ai didi

Java多线程,主线程为什么停止了?

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

我试图为 LWJGL 的 Display.update() 创建一个单独的线程,但主线程正在 sleep 或在我的第二个线程运行时停止,如何使两个线程同时执行?

public Window(int width, int height, String title){

}

@Override
public void run() {
try {
Display.setDisplayMode(new DisplayMode(800, 600));
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
}

while(!Display.isCloseRequested()){
Display.update();
Main.Render();
}

Display.destroy();

}

}

public static void main(String[] args) {
//To be moved
Window window = new Window(100, 100, "1");
Thread windowThread = new Thread(window);
windowThread.run();

System.out.print("I am workign, please show me!");
}

public static void Render(){

System.out.println("Hello There!");

}

最佳答案

改变这个,

Thread windowThread = new Thread(window);
windowThread.run();

作为,

Thread windowThread = new Thread(window);
windowThread.start();

来自Here

The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns.

The Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead.

Depending on the nature of your threaded program, calling the Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread.

关于Java多线程,主线程为什么停止了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26443831/

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