问题
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 usegameThread = new Thread() {
and then
public void run() {
while (condition) {
//code here
}
}
}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