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

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

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值