Inefficient Java program when using date

守給你的承諾、 提交于 2019-12-24 12:06:11

问题


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!");
}

回答1:


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.

See 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.




回答2:


Avoid this, use SwingTimer, swing timer not need any loop.

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

}

}




回答3:


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



回答4:


Infinite loop with tiny load (setting date) would obviously take huge CPU, introducing sleep will lessen CPU usage:

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


来源:https://stackoverflow.com/questions/17923299/inefficient-java-program-when-using-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!