2017-03-22 59 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); 
    } 
} 
相關問題