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();
}
});
}
}