i’m trying to write some “game engine” for my projects and I’m facing a problem with threads. When I create a Thread (LoadThread) in main flow, it keeps waiting until Run(); in LoadThread ends.
//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"
}
output
before
loading started
//some loaded data report, takes about 2-3s
loading done
after
Any help will be appreciated.
( little more of code http://paste.pocoo.org/show/orCfn9a8yOeEQHiUrgjG/ )
Thanks,
Vojtěch
Your problem is that you are creating a
Threadobject in your constructor but when you callstart()you are not starting the thread but running therun()method in the same thread. This looks to be confusion around extendingThreadversus implementingRunnable.What I think you should do instead is something like:
LoadThreadis the class of typeRunnablethat the thread will be executing. With your current code, when it calls:It isn’t actually starting a new Thread, it is just calling the
LoadThread.start()method which callsrun()in the same thread:Edit:
In looking more closely at your posted code in the link you provided, you are creating your
Threadobject inside of theLoadThreadconstructor. This is not a good pattern:So again, when you are calling
LoadThread.start()you aren’t starting the thread but callingrun()in the same thread. I would use thenew Thread(new LoadThread())pattern instead. If you are stuck on wrapping theThreadinside ofLoadThreadthen you should changeLoadThread.start()to be:Btw, if you want to set
runningto be false in another thread then it should be marked asvolatile.