目前,在我使用 Java 的短暂时间里,我制作了一个点击游戏,并且我一直在尝试实现一种每隔几秒将数字添加到整数(或 int 命令)的方法。但无论我尝试什么,都会完全停止整个程序,例如
Thread.sleep(15000);
wait(15000);
即使它们处于 try 和 catch 状态,它也只是停止程序而不是每隔几秒完成一个循环。
最佳答案
如果当前线程中有Thread.sleep(xxx);
,那么是的,它将停止当前线程 xxx 秒。因为(很可能)Thread.sleep
位于控制 GUI 的同一线程中,所以它会暂停代码执行,卡住应用程序。有两种方法可以解决此问题:
创建一个新线程并将计时器代码放入其中:
SwingUtilities.invokeLater 会将您的 Runnable 添加到 AWT 执行的线程队列中。
// Because the code is in a different thread, Thread.sleep(1000) will not pause
// the current thread and the application will continue as normal
Thread thread = new Thread(new Runnable() {
int seconds = 0;
@Override
public void run()
{
while (true) {
// wait one second
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
};
// increment seconds
seconds++;
System.out.println(seconds);
}
}
});
thread.start();
使用 Java API 中的现有计时器
看看ScheduledThreadPoolExecutor及其 ScheduleAtFixedRate 方法。 Here就是一个例子。您还可以使用 Hovercraft Full Of Eels 的评论中提到的 Swing 计时器。
要使用 Swing 计时器,您需要导入 javax.swing.Timer(而不是 java.util.Timer),创建一个具有延迟的 Timer 对象和一个监听何时触发事件的 Action 监听器,然后启动它。
Timer timer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent a)
{
System.out.println("Timer went off!");
}
});
// Repeat every second
timer.start();
请注意,此代码不会自行执行;您需要运行一个 GUI。
关于Java 一段代码在循环中停止而不是在 Eclipse 中停止整个程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32058626/