【问题标题】:How to run a number of task repeatedly and stop it after a certain amount of time in java如何在java中重复运行多个任务并在一定时间后停止它
【发布时间】:2018-04-09 06:46:32
【问题描述】:

我在这里和那里看到了我的答案的一部分,但不是完整的。

我知道如果你想同时运行多个任务,你想使用 ThreadRunnable 实现

我看到如果你想运行这样的重复性任务,你可以使用ScheduledExecutorService

Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);

但这只是运行一个线程,并且没有方法或参数在一定时间后杀死进程

我想做的是每 10 秒并行运行 5 次相同的任务,持续 10 分钟


编辑

如果未来的人对这里的完整示例感兴趣,那就是:

public static void main(String[] args) {
    Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
    Runnable testRunnable = () -> System.out.println("Test runnable " + LocalDateTime.now().toLocalTime().toString());

    List<Runnable> taskList = new ArrayList<>();
    taskList.add(helloRunnable);
    taskList.add(testRunnable);

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    List <ScheduledFuture<?>> promiseList = new ArrayList<>();
    for (Runnable runnable : taskList) {
        ScheduledFuture<?> promise = executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
        promiseList.add(promise);
    }

    List <Runnable> cancelList = new ArrayList<>();
    for (ScheduledFuture<?> promise : promiseList) {
        Runnable cancelRunnable = () -> {
            promise.cancel(false);
            executor.shutdown();
        };
        cancelList.add(cancelRunnable);
    }

    List <ScheduledFuture<?>> canceledList = new ArrayList<>();
    for (Runnable runnable : cancelList){
        ScheduledFuture<?> canceled = executor.schedule(runnable, 10, TimeUnit.SECONDS);
        canceledList.add(canceled);
    }
}

【问题讨论】:

    标签: java multithreading runnable scheduledexecutorservice


    【解决方案1】:

    TL;DR:安排另一个任务以取消第一个任务。

    首先,不要忽略返回值 - 这是养成的坏习惯,停止这样做并练习不这样做。 ScheduledExecutorService.scheduleAtFixedRate 方法返回 ScheduledFuture&lt;?&gt; - 这允许您取消任务!

    因此,在1 分钟内每10 秒运行一次任务:

    final Runnable helloRunnable = () -> System.out.println("Hello world " + LocalDateTime.now().toLocalTime().toString());
    final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    final ScheduledFuture<?> promise = executor.scheduleAtFixedRate(helloRunnable, 0, 10, TimeUnit.SECONDS);
    final ScheduledFuture<Boolean> canceller = executor.schedule(() -> promise.cancel(false), 1, TimeUnit.MINUTES);
    

    要注意的另一件事是,如果您从未在 Future 上调用 get,您将永远不知道任务是否失败 - 这意味着您需要 另一个 Thread 等待 @987654331 @ 以便在抛出 Exception 时立即知道出现问题。

    那么问题是who monitors the monitoring threads。因此,如果您想要一些健壮的东西,您很快就会发现自己重新实现了一个任务调度库。


    还要注意有用的实用方法Executors.newSingleThreadScheduledExecutor()

    【讨论】:

    • 正如你所说的问题是取消器本身没有被取消并且仍在运行所以你仍然有这个问题:/
    • @user3718160 为什么?它在1 分钟后运行一次 - schedule 而不是scheduleAtFixedRate
    • 我只是做了一个小例子来看看它是如何工作的,如果我每秒运行一次线程然后在 10 秒后停止它。虽然打印停止了,程序没有,它仍然在中间继续不确定地运行
    • 那是因为你需要关闭执行器。这是关于守护程序与非守护程序线程的不同问题。 TBH 正如您在上面询问的更高级的线程主题,我假设您知道这一点,并且该示例具有说明性 - 否则您需要阅读一些内容。
    • 好的,但是你如何在运行结束时关闭执行器?
    猜你喜欢
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多