gpt4 book ai didi

java - 主线程一直在等待新线程

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

我正在尝试为我的项目编写一些“游戏引擎”,但我遇到了线程问题。当我在主流程中创建一个线程(LoadThread)时,它会一直等待,直到 Run();在LoadThread结束。

//loading thread
public class LoadThread implements Runnable{
private boolean running = false;
private Thread loader = null;

public LoadThread(/*init data structures*/){
loader = new Thread(this);
}

public void start(){
running = true;
run();
}

synchronized public void run() {
System.out.println(" loading started ");
while(running){
//do some loading, when done, running = false
}
System.out.println(" loading done ");
}
}

//holds data, starts loading
public class SourceGod {
private LoadThread img_loader;
public void startLoading(){
img_loader = new LoadThread(/* some data structures */);
img_loader.start();
}
}

//runs the game
public class Game extends GameThread implements ActionListener{
private SourceGod sources;
public Game(Window full_screen){
sources = new SourceGod(/* some data structures */);
System.out.println("before");
sources.startLoading();
System.out.println("after");
}
}

//own thread to refresh
abstract public class GameThread extends JPanel implements Runnable{
//anything from there is not called before "after"
}

输出

before
loading started
//some loaded data report, takes about 2-3s
loading done
after

任何帮助将不胜感激。(更多代码 http://paste.pocoo.org/show/orCfn9a8yOeEQHiUrgjG/ )谢谢,沃伊捷赫

最佳答案

您的问题是您正在构造函数中创建一个 Thread 对象,但是当您调用 start() 时,您并没有启动线程,而是运行 run () 方法在同一个线程中。这看起来是关于扩展 Thread实现 Runnable 的混淆。

我认为你应该做的是:

// this should be of type Thread not LoadThread
private Thread img_loader;
...
// don't create the loader thread inside of LoadThread
img_loader = new Thread(new LoadThread(/* some data structures */));
img_loader.start();

LoadThread 是线程将执行的 Runnable 类型的类。使用您当前的代码,当它调用时:

img_loader.start();

它实际上并没有启动一个新线程,它只是调用 LoadThread.start() 方法,该方法在同一线程中调用 run() :

public void start(){
running = true;
run();
}

编辑:

在更仔细地查看您提供的链接中发布的代码时,您正在 LoadThread 构造函数内创建 Thread 对象。这不是一个好的模式:

public LoadThread(/*init data structures*/) {
// not recommended IMO
loader = new Thread(this);
}

再说一遍,当您调用 LoadThread.start() 时,您并不是在启动线程,而是在同一线程中调用 run()。我将使用 new Thread(new LoadThread()) 模式来代替。如果您坚持将 Thread 包裹在 LoadThread内部,那么您应该将 LoadThread.start() 更改为:

// this should be removed, you want to call Thread.start() instead
public void start(){
running = true;
// this will start the internal thread which will call run()
loader.start();
}

顺便说一句,如果您想在另一个线程中将 running 设置为 false,则应将其标记为 volatile

关于java - 主线程一直在等待新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10321704/

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