Java 如何在特定秒数后多次执行方法

Java 如何在特定秒数后多次执行方法,java,Java,我正在为计划运行使用计时器,但无法使其运行多次。我试着将整个代码放在for循环下,但这似乎不起作用,它只打印一次Hello。我做错了什么 public static void main(String[] args) throws IOException { Timer t = new Timer(); for(int i=1;i<=3;i++ ){ t.schedule(new TimerTask() {

我正在为计划运行使用计时器,但无法使其运行多次。我试着将整个代码放在for循环下,但这似乎不起作用,它只打印一次Hello。我做错了什么

 public static void main(String[] args) throws IOException {

    Timer t = new Timer();
    for(int i=1;i<=3;i++ ){
        t.schedule(new TimerTask()
                   {
                       @Override
                       public void run() {
                           System.out.println("Hello");

                           t.cancel();
                       }
                   },
                5000
        );
    }
}
更新:-来自@Ajay Kr Choudhary的解决方案有效,但对于任务终止,我更希望executorService.shutdown;或executorService.Shutdownow

编辑

根据我的理解,timer.cancel终止计时器,但循环完成。取消将阻止再次运行它,但当前循环将继续

这就是你想要实现的目标吗

public static void main(String[] args) { 

    // creating timertask, timer 
    final Timer timer = new Timer(); 
    TimerTask tt = new TimerTask() { 

        public void run() { 
            for (int i = 1; i <= 3; i++) { 
                System.out.println("working"); 
                if (i >= 1) { 
                    System.out.println("stop"); 
                    timer.cancel(); 
                } 
            } 
        }; 
    }; 
    timer.schedule(tt, 5000, 5000); 
} 
编辑

根据我的理解,timer.cancel终止计时器,但循环完成。取消将阻止再次运行它,但当前循环将继续

这就是你想要实现的目标吗

public static void main(String[] args) { 

    // creating timertask, timer 
    final Timer timer = new Timer(); 
    TimerTask tt = new TimerTask() { 

        public void run() { 
            for (int i = 1; i <= 3; i++) { 
                System.out.println("working"); 
                if (i >= 1) { 
                    System.out.println("stop"); 
                    timer.cancel(); 
                } 
            } 
        }; 
    }; 
    timer.schedule(tt, 5000, 5000); 
} 

尝试使用线程睡眠方法

public static void main(String[] args) {
    try{
        for(int i=0; i<3; i++){
            System.out.println("Hello");
            Thread.sleep(5000);
        }

    } catch(Exception e){
        System.out.println(e);
    }
}

尝试使用线程睡眠方法

public static void main(String[] args) {
    try{
        for(int i=0; i<3; i++){
            System.out.println("Hello");
            Thread.sleep(5000);
        }

    } catch(Exception e){
        System.out.println(e);
    }
}
您还可以使用ScheduledExecutorService来实现这一点。您需要调用executor服务的scheduleAtFixedRate方法。检查下面的代码片段

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SchedulerExample {
    //  counter to keep track of how many times thread has run
    static AtomicInteger runTimeCounter = new AtomicInteger(1);

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        int totalCountToRun = 3;
        int threadSleepTime = 4;
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (runTimeCounter.get() <= totalCountToRun) {
                    System.out.println("Hello");
                    System.out.println("Thread will sleep for " + threadSleepTime + " Seconds now");
                    incrementRunTimeCounter();
                } else {
                    System.out.println("Have finished running for " + totalCountToRun + " times ..." +
                            "Will exit now from the application ...");
                    System.exit(0);
                }
            }
        }, 0, threadSleepTime, TimeUnit.SECONDS);
    }

    static void incrementRunTimeCounter() {
        System.out.println(Thread.currentThread().getName() + " incrementing it to: " +
                runTimeCounter.getAndIncrement());
    }

}
您可以根据用例更改initialDelay和period参数

我们使用了AtomicInteger的概念来增加线程执行的次数。在run方法中对此计数器进行条件检查,以确保它仅在您希望它运行的次数内运行。您可以根据您的用例更改totalCountToRun变量

您也可以使用ScheduledExecutorService来实现这一点。您需要调用executor服务的scheduleAtFixedRate方法。检查下面的代码片段

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SchedulerExample {
    //  counter to keep track of how many times thread has run
    static AtomicInteger runTimeCounter = new AtomicInteger(1);

    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
        int totalCountToRun = 3;
        int threadSleepTime = 4;
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (runTimeCounter.get() <= totalCountToRun) {
                    System.out.println("Hello");
                    System.out.println("Thread will sleep for " + threadSleepTime + " Seconds now");
                    incrementRunTimeCounter();
                } else {
                    System.out.println("Have finished running for " + totalCountToRun + " times ..." +
                            "Will exit now from the application ...");
                    System.exit(0);
                }
            }
        }, 0, threadSleepTime, TimeUnit.SECONDS);
    }

    static void incrementRunTimeCounter() {
        System.out.println(Thread.currentThread().getName() + " incrementing it to: " +
                runTimeCounter.getAndIncrement());
    }

}
您可以根据用例更改initialDelay和period参数


我们使用了AtomicInteger的概念来增加线程执行的次数。在run方法中对此计数器进行条件检查,以确保它仅在您希望它运行的次数内运行。您可以根据您的用例更改totalCountToRun变量

ScheduledThreadPoolExecutor.scheduleAtFixedRate。将重复运行任务lyScheduledThreadPoolExecutor.scheduleAtFixedRate。将重复运行您的任务这不会在第二次迭代5秒后运行“我的代码”。它不会。它立即执行内部代码,而不是每五秒钟执行一次。这是另一个问题。时间表适用于计时器的延迟。如果希望循环迭代之间有延迟,可以添加睡眠。如果您愿意,我们可以继续聊天。这不会在第二次迭代5秒后运行“我的代码”。它不会。它立即执行内部代码,而不是每五秒钟执行一次。这是另一个问题。时间表适用于计时器的延迟。如果希望循环迭代之间有延迟,可以添加睡眠。如果您愿意,我们可以继续聊天。如何使其运行特定次数?参数是什么?另外,在这种情况下线程清理是如何工作的?@skr您可以使用AtomicInteger来执行此操作。我已经相应地编辑了代码。这正在工作,但不会影响System.exit0;杀死应用程序中运行的所有线程?@skr是的,你是对的。System.exit0将退出JVM本身。如果要在run方法之后继续执行,如您所说,可以使用executorService.shutdownNow;。Java中还有一个shutdownhook的概念,您可以使用它优雅地关闭正在运行的线程。许多人更喜欢这种方法来执行清理。我如何让它运行特定的次数?参数是什么?另外,在这种情况下线程清理是如何工作的?@skr您可以使用AtomicInteger来执行此操作。我已经相应地编辑了代码。这正在工作,但不会影响System.exit0;杀死应用程序中运行的所有线程?@skr是的,你是对的。System.exit0将退出JVM本身。如果要在run方法之后继续执行,如您所说,可以使用executorService.shutdownNow;。Java中还有一个shutdownhook的概念,您可以使用它优雅地关闭正在运行的线程。许多人更喜欢这种方法来执行清理。