2017-03-22 56 views
0

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

+3

这是否帮助:http://stackoverflow.com/questions/30649643/scheduledexecutorservice-and-threadpooltaskexecutor-that-interrupts-tasks-after或:http://stackoverflow.com/questions/2758612/ executorservice-that-interrupts-tasks-after-a-timeout ......提示:我只是简单地把你的问题标题放到谷歌去那里......“先前的研究事物”是一种有力的武器,我告诉你! – GhostCat

+0

正如GhostCat所述,您应该首先使用google来了解如何解决您的问题。当你尝试了一些东西并且不能按预期工作时,请随时在此发布代码并寻求帮助 – JanTheGun

+0

感谢您的参考。我决定在研究后在这里发布这个问题。我已经阅读了第一本,但由于某种原因,我跳过了第二本。这可能是我一直在寻找的。谢谢! –

回答

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); 
    } 
} 
相关问题