gpt4 book ai didi

java - 使用线程按固定时间间隔调用函数

转载 作者:行者123 更新时间:2023-12-02 04:28:06 25 4
gpt4 key购买 nike

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

定时器.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());
}
}

NewJFrame.java

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

之后,我在 00:00:30 秒停止线程,因此我将得到以下输出:

Stop Time ===============> Sat Aug 08 10:46:31 IST 2015

我已在 00:00:30 秒停止线程,但我的函数在 00:00:30 秒后自动调用

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

最佳答案

正确答案是:不要使用线程。根据您希望Thread 执行的操作,使用TimerSwingTimerScheduledExecutorService

要回答您想要的实际问题,请检查 isRunning 并在 sleep 完成后立即退出。如果您愿意,您还可以向线程发送中断,使 sleep 立即停止。

关于java - 使用线程按固定时间间隔调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com