起初,我這樣做:在Java中,爲什麼我的多線程不工作?
public SpaceCanvas(){
new Thread(new Runnable() {//this is the thread that triggers updates, no kidding
int fcount = 0;
@Override
public void run() {
System.out.println("Update thread started!");
while(!Thread.interrupted()){
fcount++;
while(players.iterator().hasNext()){
players.iterator().next().update(fcount);
}
while(entities.iterator().hasNext()){
entities.iterator().next().update(fcount);
}
System.out.println("About to paint");
repaint();
System.out.println("Done with paints");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
players.add(new LocalPlayer(0, 9001, 0, 0, 0, 0, this, null));
}
在我稱之爲SpaceCanvas事初始化。 但是,這不允許創建畫布,因此它創建的小程序,因爲線程不實際上異步運行。然後,我用「.run()」替換了「.start()」,該線程只運行一次,但SpaceCanvas完全初始化。
我做錯了什麼,我該如何解決這個問題?
我會盡快嘗試這個,謝謝。 – striking
你也可以使用'for(Iterator i = players.iterator(); i.hasNext();)i.next()。update(fcount);' –
OldCurmudgeon