ExecutorService that interrupts tasks after a timeout

后端 未结 9 2323
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 16:19

I\'m looking for an ExecutorService implementation that can be provided with a timeout. Tasks that are submitted to the ExecutorService are interrupted if they take longer t

9条回答
  •  长发绾君心
    2020-11-22 16:40

    You can use a ScheduledExecutorService for this. First you would submit it only once to begin immediately and retain the future that is created. After that you can submit a new task that would cancel the retained future after some period of time.

     ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
     final Future handler = executor.submit(new Callable(){ ... });
     executor.schedule(new Runnable(){
         public void run(){
             handler.cancel();
         }      
     }, 10000, TimeUnit.MILLISECONDS);
    

    This will execute your handler (main functionality to be interrupted) for 10 seconds, then will cancel (i.e. interrupt) that specific task.

提交回复
热议问题