线程导致高CPU使用率

时间:2015-02-27 10:30:32

标签: java frame cpu dispose

我是Java的初学者。我的程序处理当前帧并在单击按钮时调用新帧。问题是,如果我连续不停地使用这个程序,CPU使用率会持续增加,直到它最终滞后并使用高达99%的CPU!我不知道为什么会这样。请帮忙!

编辑:我发现了问题,它用这个线程让我的时钟更新!我已经尝试在处理表单时停止该线程,但这似乎不起作用。知道我应该做什么吗?

private volatile boolean isRunning = true;


new Thread()
    {

        public void run()
        {

            while (isRunning)
            {

                Calendar cal = new GregorianCalendar();

                hour = cal.get(Calendar.HOUR);
                minutes = cal.get(Calendar.MINUTE);
                seconds = cal.get(Calendar.SECOND);
                am_pm = cal.get(Calendar.AM_PM);
                day = cal.get(Calendar.DAY_OF_WEEK);
                dayofmonth = cal.get(Calendar.DAY_OF_MONTH);
                month = cal.get(Calendar.MONTH) + 1;
                year = cal.get(Calendar.YEAR);

                if(am_pm == 1)
                {

                    hour = hour + 12;

                }

                else
                {
                    if(hour == 12)
                    {

                        hour = hour - 12;
                    }  

                    else
                    {

                     hour = hour;   
                    }
                }

                String time = hour + ":" + minutes + ":" + seconds;
                String date = dayofmonth + "/" + month + "/" + year;

                Clock.setText(time);
                Date.setText(date);

            }



            public void kill(){

            isRunning = false;

            }

            kill();
            this.dispose();
            new PaymentForm().setVisible(true);

这是整个RegistrationForm的代码。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package car.parking.auto.pay.station;

import com.sun.glass.events.KeyEvent;
import java.awt.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;

/**
 *
 * @author superbad95
 */
public class RegistrationForm extends javax.swing.JFrame {

    
        private volatile boolean isRunning = true; //A condition for the while loop to continue for refreshing the clock.
        int hour;       //Hour variable to store the hour of the current system time.
        int minutes;    //Minutes variable to store the minutes of the current system time.
        int seconds;    //Seconds variable to store the seconds of the current system time.
        int am_pm;      //AM_PM variable to store the AM/PM.
        
        int day;        //Day variable to store the current day of the week.
        int dayofmonth; //Variable to store the day of the month.
        int month;      //Variable to store the month.
        int year;       //Variable to store the year.
        
        public static String Carplate; //A global variable to store the text from CarplateTxt.
        String Temp;
        
        JFrame frame = new JFrame();
        
        
        
    
        
    
    public RegistrationForm() {
        initComponents();
        
        Error.setText("");
        
        new Thread()
        {
        
            public void run()
            {
            
                while (isRunning)
                {
                
                    Calendar cal = new GregorianCalendar();
                    
                    hour = cal.get(Calendar.HOUR);
                    minutes = cal.get(Calendar.MINUTE);
                    seconds = cal.get(Calendar.SECOND);
                    am_pm = cal.get(Calendar.AM_PM);
                    day = cal.get(Calendar.DAY_OF_WEEK);
                    dayofmonth = cal.get(Calendar.DAY_OF_MONTH);
                    month = cal.get(Calendar.MONTH) + 1;
                    year = cal.get(Calendar.YEAR);
                    
                    if(am_pm == 1)
                    {
                    
                        hour = hour + 12;
                        
                    }
                    
                    else
                    {
                        if(hour == 12)
                        {
                        
                            hour = hour - 12;
                        }  
                        
                        else
                        {
                        
                         hour = hour;   
                        }
                    }
                    
                    String time = hour + ":" + minutes + ":" + seconds;
                    String date = dayofmonth + "/" + month + "/" + year;
                    
                    Clock.setText(time);
                    Date.setText(date);
                    
                }
            }
        
        }.start();
        
        
        
        
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        Clock = new javax.swing.JLabel();
        CarplateTxt = new javax.swing.JTextField();
        CheckOutBtn = new javax.swing.JButton();
        CheckInBtn = new javax.swing.JButton();
        Date = new javax.swing.JLabel();
        Error = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        Clock.setFont(new java.awt.Font("Roboto Thin", 0, 36)); // NOI18N
        Clock.setText("18:32:12");

        CarplateTxt.setFont(new java.awt.Font("Roboto Thin", 0, 36)); // NOI18N
        CarplateTxt.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                CarplateTxtFocusLost(evt);
            }
        });
        CarplateTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                CarplateTxtKeyTyped(evt);
            }
        });

        CheckOutBtn.setFont(new java.awt.Font("Roboto Light", 0, 24)); // NOI18N
        CheckOutBtn.setText("Check-Out");
        CheckOutBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckOutBtnActionPerformed(evt);
            }
        });

        CheckInBtn.setFont(new java.awt.Font("Roboto Light", 0, 24)); // NOI18N
        CheckInBtn.setText("Check-In");
        CheckInBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CheckInBtnActionPerformed(evt);
            }
        });

        Date.setFont(new java.awt.Font("Roboto Thin", 0, 18)); // NOI18N
        Date.setText("24/2/2015");

        Error.setFont(new java.awt.Font("Roboto Light", 0, 11)); // NOI18N
        Error.setForeground(java.awt.Color.red);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(70, 70, 70)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(CheckOutBtn)
                    .addComponent(CheckInBtn)
                    .addComponent(Clock)
                    .addComponent(CarplateTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(Date)
                    .addComponent(Error))
                .addContainerGap(70, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {CheckInBtn, CheckOutBtn});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(132, Short.MAX_VALUE)
                .addComponent(Date)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Clock)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CarplateTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(Error)
                .addGap(5, 5, 5)
                .addComponent(CheckInBtn)
                .addGap(18, 18, 18)
                .addComponent(CheckOutBtn)
                .addGap(20, 20, 20))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {CarplateTxt, Clock});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {CheckInBtn, CheckOutBtn});

        pack();
    }// </editor-fold>                        

    private void CheckInBtnActionPerformed(java.awt.event.ActionEvent evt) {                                           
        
        Carplate = CarplateTxt.getText().toUpperCase();
        
        if (Carplate.length() < 2)
        {
            Error.setText("Please enter a valid Carplate number.");
            CarplateTxt.requestFocus();
        }
        
        else
        {
            Error.setText("");
            File temp = new File ("");
            Temp = temp.getAbsolutePath();
            File file = new File (Temp+"//Files//Details//"+Carplate+".txt");
            
            if(file.exists())
            {
            
                try{
                    Scanner input = new Scanner(file);
                    
                    Car_Information.Carplate = input.nextLine();
                    
                    Car_Information.CheckInDate = input.nextLine();
                    
                    Car_Information.CheckInTime = input.nextLine();
                    
                    Car_Information.CheckInHour = input.nextInt();
                    Car_Information.CheckInMinute = input.nextInt();
                    Car_Information.CheckInMinuteTime = input.nextInt();
                    
                    Car_Information.CheckInDay = input.nextInt();
                    Car_Information.CheckInDayofthemonth = input.nextInt();
                    Car_Information.CheckInMonth = input.nextInt();
                    Car_Information.CheckInYear = input.nextInt();
                    
                    
                }catch(IOException ex)
                {System.out.printf("ERROR: %s\n", ex);}
                
                JOptionPane.showMessageDialog(frame, Car_Information.Carplate + " has already been registered at " +Car_Information.CheckInTime+ " On " +Car_Information.CheckInDate + ". Please Check-out the vehicle.");
                
                
                
            }
            
            else
            {
            
                Car_Information.Carplate = Carplate;
            
                Car_Information.CheckInHour = hour;
                Car_Information.CheckInMinute = minutes;
                Car_Information.CheckInDay = day;
                
                Car_Information.CheckInDayofthemonth = dayofmonth;
                Car_Information.CheckInMonth = month;
                Car_Information.CheckInYear = year;
                
                Car_Information.CheckInTimeChange(Car_Information.CheckInHour, Car_Information.CheckInMinute);
                
                Car_Information.CheckInMinuteTimeConversion(Car_Information.CheckInHour,Car_Information.CheckInMinute);
                
                Car_Information.CheckInDateConversion(Car_Information.CheckInDayofthemonth, Car_Information.CheckInMonth, Car_Information.CheckInYear);
                
                try{
                    
                    PrintWriter output = new PrintWriter(file);
                    
                    output.println(Car_Information.Carplate);
                    output.println(Car_Information.CheckInDate);
                    output.println(Car_Information.CheckInTime);
                    
                    output.println(Car_Information.CheckInHour);
                    output.println(Car_Information.CheckInMinute);
                    output.println(Car_Information.CheckInMinuteTime);
                    
                    output.println(Car_Information.CheckInDay);
                    output.println(Car_Information.CheckInDayofthemonth);
                    output.println(Car_Information.CheckInMonth);
                    output.println(Car_Information.CheckInYear);
                    
                    output.close();
                
                }catch(IOException ex)
                {System.out.printf("ERROR: %s\n", ex);}

                JOptionPane.showMessageDialog(frame, Car_Information.Carplate + " has been registered at " + Car_Information.CheckInTime);}
            }
                
            
            
        
        
        
    }                                          

    private void CarplateTxtKeyTyped(java.awt.event.KeyEvent evt) {                                     
        
        Carplate = CarplateTxt.getText().toUpperCase();
        
        char verif = evt.getKeyChar();
        
        if(!(Character.isDigit(verif) || Character.isAlphabetic(verif) || (verif == KeyEvent.VK_BACKSPACE)))
        {
        
            Error.setText("Please enter a valid Carplate number.");
            getToolkit().beep();
            evt.consume();
        }
        
        else
        {
            Error.setText("");
        }
        
        if (Carplate.length() > 6)
        {
            Error.setText("Please enter a valid Carplate number.");
            getToolkit().beep();
            evt.consume();
        }
        
        else
        {
        
            Error.setText("");
        }
            
            
    }                                    

    private void CarplateTxtFocusLost(java.awt.event.FocusEvent evt) {                                      
        
        if (CarplateTxt.getText().length() < 2)
        {
            getToolkit().beep();
        }
        
        
    }                                     

    private void CheckOutBtnActionPerformed(java.awt.event.ActionEvent evt) {                                            

        Carplate = CarplateTxt.getText().toUpperCase();
        
        if (Carplate.length() < 2)
        {
            Error.setText("Please enter a valid Carplate number.");
            CarplateTxt.requestFocus();
        }
        else{
        File temp = new File ("");
        Temp = temp.getAbsolutePath();
        File file = new File (Temp+"//Files//Details//"+Carplate+".txt");
        
        if(file.exists())
        {
            Car_Information.CheckOutDayofthemonth = dayofmonth;
            Car_Information.CheckOutMonth = month;
            Car_Information.CheckOutYear = year;
            
            Car_Information.CheckOutHour = hour;
            Car_Information.CheckOutMinute = minutes;
            
            Car_Information.CheckOutDateConversion(Car_Information.CheckOutDayofthemonth, Car_Information.CheckOutMonth,Car_Information.CheckOutYear);
            Car_Information.CheckOutMinuteTimeConversion(Car_Information.CheckOutHour,Car_Information.CheckOutMinute);
            Car_Information.CheckOutTimeChange(Car_Information.CheckOutHour,Car_Information.CheckOutMinute);
            
            try{
                    Scanner input = new Scanner(file);
                    
                    Car_Information.Carplate = input.nextLine();
                    Car_Information.CheckInDate = input.nextLine();
                    
                    
                }catch(FileNotFoundException ex)
                {System.out.printf("ERROR: %s\n", ex);}
            
            if(!Car_Information.CheckInDate.equals(Car_Information.CheckOutDate))
            {
            
                JOptionPane.showMessageDialog(frame, "Your car was registered on " + Car_Information.CheckInDate + ", please contact authorities for further instructions.");
            }
            
            else
            {
        
            kill();
            this.dispose();
            new PaymentForm().setVisible(true);
            
            }
                    
                    
        
        }
        
        else
        {
        
            JOptionPane.showMessageDialog(frame,"This vehicle is not registered.");
        }
        
        
        
        
        }   
    }                                           
 
 
    public void kill(){
    
    isRunning = false;
    
    }
    
    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(RegistrationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(RegistrationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(RegistrationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(RegistrationForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RegistrationForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JTextField CarplateTxt;
    private javax.swing.JButton CheckInBtn;
    private javax.swing.JButton CheckOutBtn;
    private javax.swing.JLabel Clock;
    private javax.swing.JLabel Date;
    private javax.swing.JLabel Error;
    // End of variables declaration                   
}

0 个答案:

没有答案