Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用线程在固定时间间隔上调用函数_Java_Multithreading_Swing_Timer_Java Threads - Fatal编程技术网

Java 使用线程在固定时间间隔上调用函数

Java 使用线程在固定时间间隔上调用函数,java,multithreading,swing,timer,java-threads,Java,Multithreading,Swing,Timer,Java Threads,我想在特定的时间间隔调用我的函数。现在我的时间间隔定为1分钟。我有以下代码示例: Timer.java import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; public class Timer implements Runnable{ public static volatile boolean isRunning = true; @Override

我想在特定的时间间隔调用我的函数。现在我的时间间隔定为1分钟。我有以下代码示例:

Timer.java

import java.util.Date;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Timer implements Runnable{
    public static volatile boolean isRunning = true;

    @Override
    public void run() {
        while (isRunning) {    
            if(Thread.currentThread().getName().equals("TimerThread")){
                System.out.println("Start Time "+new Date());

                try {
                    test();
                    Thread.sleep(60000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
                }

                System.out.println("End Time "+new Date());    
            }
        }
    }

    public void test(){
        System.out.println("Call Test ===========================> "+new Date());
    }
}
import java.awt.event.ItemEvent;

import java.util.Date;

public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * 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() {

        jToggleButton1 = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToggleButton1.setText("Start");
        jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jToggleButton1ItemStateChanged(evt);
            }
        });

        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(162, 162, 162)
                .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(138, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(129, 129, 129)
                .addComponent(jToggleButton1)
                .addContainerGap(142, Short.MAX_VALUE))
        );

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

    private void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt) {                                                
        // TODO add your handling code here:
        if(evt.getStateChange() == ItemEvent.SELECTED){
            jToggleButton1.setText("Stop");
            timer = new Timer();
            timer.isRunning = true;
            timerThread = new Thread(timer);
            timerThread.setName("TimerThread");
            timerThread.start();
        }else{
            jToggleButton1.setText("Start");
            timer.isRunning = false;
            System.out.println("Stop Time ===============> "+new Date());
        }
    }                                               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    public Timer timer;
    public Thread timerThread;
    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration                   
}
NewJFrame.java

import java.util.Date;

import java.util.logging.Level;

import java.util.logging.Logger;

public class Timer implements Runnable{
    public static volatile boolean isRunning = true;

    @Override
    public void run() {
        while (isRunning) {    
            if(Thread.currentThread().getName().equals("TimerThread")){
                System.out.println("Start Time "+new Date());

                try {
                    test();
                    Thread.sleep(60000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Timer.class.getName()).log(Level.SEVERE, null, ex);
                }

                System.out.println("End Time "+new Date());    
            }
        }
    }

    public void test(){
        System.out.println("Call Test ===========================> "+new Date());
    }
}
import java.awt.event.ItemEvent;

import java.util.Date;

public class NewJFrame extends javax.swing.JFrame {

    /**
     * Creates new form NewJFrame
     */
    public NewJFrame() {
        initComponents();
    }

    /**
     * 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() {

        jToggleButton1 = new javax.swing.JToggleButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToggleButton1.setText("Start");
        jToggleButton1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jToggleButton1ItemStateChanged(evt);
            }
        });

        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(162, 162, 162)
                .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(138, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(129, 129, 129)
                .addComponent(jToggleButton1)
                .addContainerGap(142, Short.MAX_VALUE))
        );

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

    private void jToggleButton1ItemStateChanged(java.awt.event.ItemEvent evt) {                                                
        // TODO add your handling code here:
        if(evt.getStateChange() == ItemEvent.SELECTED){
            jToggleButton1.setText("Stop");
            timer = new Timer();
            timer.isRunning = true;
            timerThread = new Thread(timer);
            timerThread.setName("TimerThread");
            timerThread.start();
        }else{
            jToggleButton1.setText("Start");
            timer.isRunning = false;
            System.out.println("Stop Time ===============> "+new Date());
        }
    }                                               

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.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 NewJFrame().setVisible(true);
            }
        });
    }
    public Timer timer;
    public Thread timerThread;
    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration                   
}
一旦时间间隔完成,我将获得以下输出:

Start Time Sat Aug 08 10:45:01 IST 2015
Call Test ===========================> Sat Aug 08 10:45:01 IST 2015
End Time Sat Aug 08 10:46:01 IST 2015
Start Time Sat Aug 08 10:46:01 IST 2015
Call Test ===========================> Sat Aug 08 10:46:01 IST 2015
Stop Time ===============> Sat Aug 08 10:46:31 IST 2015
之后,我在00:00:30秒停止线程,因此我将获得以下输出:

Start Time Sat Aug 08 10:45:01 IST 2015
Call Test ===========================> Sat Aug 08 10:45:01 IST 2015
End Time Sat Aug 08 10:46:01 IST 2015
Start Time Sat Aug 08 10:46:01 IST 2015
Call Test ===========================> Sat Aug 08 10:46:01 IST 2015
Stop Time ===============> Sat Aug 08 10:46:31 IST 2015
我已在00:00:30秒停止线程,但我的函数在00:00:30秒后自动调用


任何人都可以帮助我,我如何使用线程固定时间间隔调用任何函数,就像我单击开始按钮一样,等待2分钟后,我的线程将启动并调用函数。2分钟后再次调用我的函数并重复循环。如果单击“停止”按钮,线程将停止,直到使用“开始”按钮启动线程。

正确答案是:不要使用
线程。根据您希望
线程执行的操作,使用
计时器
旋转计时器
调度执行器服务


要回答实际问题,请选中
isRunning
,并在睡眠完成后立即退出。如果需要,您还可以向线程发送中断,使睡眠立即停止。

简短回答是,更好的回答,使用Swing
计时器
您的问题到底是什么?你的代码有什么问题?你期望发生什么而不是看到什么?当我停止线程时,那么为什么在00:00:30秒后调用函数呢?根据你发布的输出,它没有。停止线程,在输出中获得停止时间,仅此而已。如果这是错误的,发布您的所有输出。当我停止我的线程时,然后按如下方式输出:停止时间=================>2015年8月8日星期六10:46:31 IST,但当在00:00:30秒后停止线程时,我会得到以下输出:开始时间星期六8月8日10:47:01 IST 2015调用测试==========================>2015年8月8日星期六10:47:01 IST平均线程在00:00:30秒