简体   繁体   English

使用ScheduledExecutorService,如何在不等待其他线程按固定间隔完成的情况下启动线程?

[英]Using ScheduledExecutorService, How to Start a Thread without waiting for other thread to complete at fixed interval?

I want to run a task at every particular interval of time regardless of completion of previous thread. 我想在每个特定的时间间隔运行任务,而不管以前的线程是否完成。 And I've used ScheduledExecutorService with the schedule time at every one second. 而且我已将ScheduledExecutorService与计划时间一秒使用。 But the problem is, in my Runnable, If I make thread to sleep for 5 seconds, My ScheduledExecuterService also getting executed in every 5 seconds while it supposed to run each thread at 1 second. 但是问题是,在我的Runnable中,如果我使线程休眠5秒钟,则我的ScheduledExecuterService也每5秒执行一次,而它应该在1秒内运行每个线程。

It seems like it ScheduledExecuterService is waiting for previous thread to completion. 看来ScheduledExecuterService正在等待上一个线程完成。 But I want, The task to be triggered at every 1 second no matter what if job inside the task waits for longer time. 但是我想,无论任务中的作业等待更长的时间如何,任务都会每1秒触发一次。

Here's is my code. 这是我的代码。

public class MyTask implements Runnable {

   public void run() {
       System.out.println("hi there at: "+ new java.util.Date());
       try {
           Thread.sleep(5000);
       } catch (InterruptedException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }
}

And here's my ScheduledExecutorService Code. 这是我的ScheduledExecutorService代码。

public class JavaScheduledExecutorServiceExample {

   public static void main(String[] args) {
       ScheduledExecutorService execService = Executors.newScheduledThreadPool(5);
       execService.scheduleAtFixedRate(new MyTask(), 0, 1000, TimeUnit.MILLISECONDS);
   }
}

Correct me If I'm doing something wrong. 纠正我,如果我做错了。 And If I'm wrong, is there any alternative to achieve the same? 如果我错了,是否有其他选择可以实现相同目标? Providing Any best practices could be more helpful :) 提供任何最佳做法可能会更有帮助:)

" If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute. " The behavior you are seeing is consistent with the javadocs 如果此任务的任何执行花费的时间超过其时间,那么后续执行可能会延迟执行,但不会同时执行。 ”您所看到的行为与javadocs一致

I believe this will perform the way you specified: 相信这将按照您指定的方式执行:

public class JavaScheduledExecutorServiceExample {
    private static ScheduledExecutorService execService = null;
    private static int timesAsleep = 0;

    public static class MyTask implements Runnable {

        public void run() {
            System.out.println("hi there at: "+ new java.util.Date());
            // schedule again
            execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS);
            try {
                int i = timesAsleep;
                timesAsleep++;
                System.out.println("asleep " + i + "----------------------");
                Thread.sleep(5000);
                System.out.println("awoke " + i + "----------------------");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        execService = Executors.newScheduledThreadPool(5);
        execService.schedule(new MyTask(), 1000, TimeUnit.MILLISECONDS);
    }

}

Notice the use schedule() instead of scheduleAtFixedRate() on the ScheduledExecutorService instance. 注意,在ScheduledExecutorService实例上使用了schedule()而不是scheduleAtFixedRate() It also schedules the next task as soon as it starts the new task. 它还会在开始任务时安排下一个任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java ScheduledExecutorService.scheduleWithFixedDelay启动新线程以执行任务,而无需等待第一个任务完成 - Java ScheduledExecutorService.scheduleWithFixedDelay starts new thread to execute the task without waiting for 1st task to complete 如何从应用程序启动时运行固定间隔的线程? - How to run a fixed interval thread from start of app? 如何在已关闭的ScheduledExecutorService中保持线程等待 - How to keep thread waiting in ScheduledExecutorService that has been shutdown 添加延迟以使用ScheduledExecutorService对象启动执行线程 - Add delay to start execution thread with ScheduledExecutorService object 如何使用Scheduledexecutorservice强制创建一个线程并避免多线程 - How to force to create a single thread using scheduledexecutorservice and avoid multithreading ThreadpoolExecutor,正在运行的线程之一引发异常时,等待其他正在运行的线程完成 - ThreadpoolExecutor , Waiting for other running thread to complete when one of the running thread throws exception 如何在不等待客户端响应的情况下停止线程 - How to stop thread without waiting client response 如何在不使用Timer或其他线程的情况下在Java线程中的给定时间间隔内安排任务? - How to schedule a task on a given interval of time in a thread in java without using Timer or another thread? 如何在不使用ExecutorService的情况下实现固定线程池 - How to achieve fixed thread pool without using ExecutorService 唤醒使用 ScheduledExecutorService 生成的线程 - Wake up a thread spawned using ScheduledExecutorService
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM