ScheduledExecutorService在超时后中断

时间:2017-03-22 08:47:57

标签: java multithreading java-threads

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

1 个答案:

答案 0 :(得分:1)

这有用吗?任务每10秒开始一次,完成需要5秒钟,你会在timedout(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);
    }
}