我的程序似乎使用了 20% 的 CPU 和大约 1GB 的 RAM。我认为这是因为我正在循环日期。我试图让一个时钟出现在我的 JFrame 上(小时、分钟和秒总是更新)。我的问题是,如何让我的程序不那么耗电? 这是我的代码:
while(true){
Date date = new Date();
time.setText(date.getHours() + " hours " + date.getMinutes()
+ " minutes " + date.getSeconds() + " seconds!");
}
最佳答案
如何让我的程序不那么耗电?让你的线程 hibernate 一会儿。 我假设给定的代码@Cj1m 是在新启动的线程中运行的。
参见 java.lang.Thread.sleep(long)
while(true){
SwingUtilities.invokeLater(new Runnable(){ // make sure to run in EDT
@Override
public void run(){
Date date = new Date();
time.setText(date.getHours() + " hours " + date.getMinutes()
+ " minutes " + date.getSeconds() + " seconds!");
}
});
try {
Thread.sleep(1000); // Sleep for 1000 milliseconds.
// Give a shorter interval if you like.
} catch(InterruptedException e) { // Who interrupted my dream?
e.printStackTrace();
}
}
或者按照其他人的描述使用 Swing Timer。
关于java - 使用日期时 Java 程序效率低下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17923299/