While loop makes applet white screen and unresponsive

不问归期 提交于 2019-12-12 03:54:15

问题


Here is my loop code (This is the only code relating to my loop):

while(true)
    {
        try {
            Thread.sleep(20);
            System.out.println("1");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }           
    }

When I launch the applet, it white screens and I cannot close it unless I press the "Terminate" button in eclipse.


回答1:


You're blocking the UI Thread with an infinite while loop. You don't say whether you're using an AWT or Swing applet, either way the result will be the same. If you're using a Swing applet, use a Swing Timer. If you're using the old heavyweight AWT, convert it to Swing and follow the previous advice.




回答2:


As said you made an infinity loop with:

while(true){
//something
}

There is no break; So why or what should stop the loop except of a thrown exception?

To see when a InterruptedException is thrown you should read the JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/lang/InterruptedException.html




回答3:


You are hogging the applets EDT. You need to run your loop in another thread. Try adding Thread gameThread; as a variable and use
gameThread = new Thread() {
public void run() {
while (condition) {
//code here
}
}
}
and then gameThread.start() both in your applet start method and gameThread.join() in your applet stop method.



来源:https://stackoverflow.com/questions/16369264/while-loop-makes-applet-white-screen-and-unresponsive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!