My program seem to be using 20% of the CPU and around 1GB of RAM. I think its because I am looping the date. I am trying to make a clock appear on my JFrame (hours, mins and seconds always updating). My question is, how can I make my program less hungry for power?
Here's my code:
while(true){
Date date = new Date();
time.setText(date.getHours() + " hours " + date.getMinutes()
+ " minutes " + date.getSeconds() + " seconds!");
}
解决方案
Don't loop. Whatever the application, the above infinite loop will place a constant demand on resources.
In this case, it appears you are using Swing. This is even worse for Swing applications. Infinite loops prevent UI updates.
Use a Swing Timer instead and set an period interval large enough that will allow updates to be observed and will demand less overhead from the CPU. 1000 milliseconds should do.
public class TimerDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Timer Demo");
final JLabel timeLabel =
new JLabel("-----------------------------------------------");
Timer timer = new Timer(1000, new ActionListener() {
SimpleDateFormat format = new SimpleDateFormat("HH' hours 'mm' minutes 'ss' seconds'");
@Override
public void actionPerformed(ActionEvent e) {
Date date = new Date();
timeLabel.setText(format.format(date));
}
});
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(timeLabel);
frame.setVisible(true);
frame.pack();
timer.start();
}
});
}
}
博客指出了一种常见问题,即在Java Swing应用程序中使用无限循环导致高CPU和内存占用。作者建议不要使用无限循环,并推荐使用SwingTimer来定期更新UI,如时钟显示。SwingTimer允许设置适当间隔,减少对CPU的负担,同时确保UI的正常更新。提供的代码示例展示了如何用SwingTimer实现时钟功能。
725

被折叠的 条评论
为什么被折叠?



