【问题标题】:ScheduledExecutorService that interrupts after a timeoutScheduledExecutorService 在超时后中断
【发布时间】:2017-05-24 23:05:07
【问题描述】:

我需要实现一个预定的执行器服务,它每隔 x 秒运行一个线程。 如果线程执行时间超过 y 秒,则应中断线程执行。 我尝试使用 ScheduledExecutorService 来实现解决方案,该服务具有可配置的间隔参数,但没有可配置的超时参数。 我有一些想法,我想听听您对实现/技术的建议。

【问题讨论】:

  • 这个有帮助吗:stackoverflow.com/questions/30649643/… 或者那个:stackoverflow.com/questions/2758612/… ...并提示:我只是把你的问题标题放到谷歌中去那里......“先前的研究”是一个强大的武器,我告诉你!
  • 正如 GhostCat 已经说过的,你应该首先使用谷歌来了解如何解决你的问题。当您尝试了某些东西但没有按预期工作时,请随时在此处发布代码并寻求帮助
  • 感谢您的参考。在进行研究后,我决定在这里发布问题。我已经阅读了第一个,但由于某种原因,我跳过了第二个。这可能是我一直在寻找的。谢谢!

标签: java multithreading java-threads


【解决方案1】:

这有帮助吗?任务每 10 秒开始一次,需要 5 秒才能完成,超时(3 秒)你会得到一个 InterruptedException。

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Worker implements Runnable {
    ListeningExecutorService listeningExecutorService;
    ScheduledExecutorService scheduledExecutorService;
    Runnable task;

    public Worker(ListeningExecutorService listeningExecutorService, ScheduledExecutorService scheduledExecutorService, Runnable task) {
        this.listeningExecutorService = listeningExecutorService;
        this.scheduledExecutorService = scheduledExecutorService;
        this.task = task;
    }

    @Override
    public void run() {
        ListenableFuture future = listeningExecutorService.submit(task);
        Futures.withTimeout(future, 3, TimeUnit.SECONDS, scheduledExecutorService);
    }

    public static void main(String[] args) {
        ListeningExecutorService listeningExecutorService = MoreExecutors
            .listeningDecorator(Executors.newCachedThreadPool());
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        Worker worker = new Worker(listeningExecutorService, scheduledExecutorService, new Runnable() {
            @Override
            public void run() {
                System.out.println("Now begin: " + new Date());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Now end: " + new Date());
            }
        });
        scheduledExecutorService.scheduleAtFixedRate(worker, 0, 10, TimeUnit.SECONDS);
    }
}

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2012-12-04
    相关资源
    最近更新 更多