简体   繁体   English

使用日期时Java程序效率低下

[英]Inefficient Java program when using date

My program seem to be using 20% of the CPU and around 1GB of RAM. 我的程序似乎正在使用20%的CPU和大约1GB的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). 我试图使时钟出现在我的JFrame上(小时,分钟和秒总是更新)。 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. 在这种情况下,您似乎正在使用Swing。 This is even worse for Swing applications. 对于Swing应用程序,这甚至更糟。 Infinite loops prevent UI updates. 无限循环会阻止UI更新。

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. 请改用Swing计时器,并设置一个足够大的周期间隔,这样就可以观察到更新,并要求CPU减少开销。 1000 milliseconds should do. 应该做到1000毫秒。

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

Avoid this, use SwingTimer , swing timer not need any loop. 避免这种情况,使用SwingTimer ,swing计时器不需要任何循环。

Here a full example: 这里是一个完整的例子:

import java.util.*;
import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
public class DateAndTimer extends JFrame {
 private javax.swing.Timer timer;
 private JLabel label ;
 private Date ;
 public DateAndTimer(){
  this.timer = new javax.swing.Timer(1000,getActionTimer());
  date = new Date();
  label = new JLabel();
  add(label,BorderLayout.PAGE_START);
  timer.start();
  setDefaultCloseOperation(3);
  setVisible(true);
  pack();

 }

 public ActionListener getActionTimer(){
  ActionListener action = new ActionListener(){
  @Override
  public void actionPerformed(ActionEvent e){

      label.setText(date.getHours() + " hours " + date.getMinutes()
                 + " minutes " + date.getSeconds() + " seconds!");
 }
 };
 return action;
}

public static void main(String...args){
    SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run(){
           new DateAndTimer();
    }
    });

}

} }

How can I make my program less hungry for power? 如何减少程序对电源的需求? Make your thread sleep for a while. 使您的线程休眠一会儿。 I assumed the code @Cj1m given is run in a newly started thread. 我假设给定的代码@ Cj1m在新启动的线程中运行。

See java.lang.Thread.sleep(long) 参见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();
    }
}

Or use Swing Timer as others described. 或使用其他描述的Swing计时器。

Infinite loop with tiny load (setting date) would obviously take huge CPU, introducing sleep will lessen CPU usage: 负载很小(设置日期)的无限循环显然会占用大量CPU,而引入sleep会减少CPU使用率:

while(true){
    Date date = new Date();
    time.setText(date.getHours() + " hours " + date.getMinutes() 
                 + " minutes " + date.getSeconds() + " seconds!");
    Thread.sleep(1000);//1second update of clock
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM