java 日期比较效率,使用日期时效率低下的Java程序

博客指出了一种常见问题,即在Java Swing应用程序中使用无限循环导致高CPU和内存占用。作者建议不要使用无限循环,并推荐使用SwingTimer来定期更新UI,如时钟显示。SwingTimer允许设置适当间隔,减少对CPU的负担,同时确保UI的正常更新。提供的代码示例展示了如何用SwingTimer实现时钟功能。

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

}

});

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值