2011-07-21 84 views
8

我寫了下面的代碼:的ScheduledThreadPoolExecutor,如何停止運行的類JAVA

import java.util.Calendar; 
import java.util.concurrent.ScheduledThreadPoolExecutor; 
import java.util.concurrent.TimeUnit; 

class Voter { 
public static void main(String[] args) { 
    ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2); 
    stpe.scheduleAtFixedRate(new Shoot(), 0, 1, TimeUnit.SECONDS); 
} 
} 

class Shoot implements Runnable { 
Calendar deadline; 
long endTime,currentTime; 

public Shoot() { 
    deadline = Calendar.getInstance(); 
    deadline.set(2011,6,21,12,18,00); 
    endTime = deadline.getTime().getTime(); 
} 

public void work() { 
    currentTime = System.currentTimeMillis(); 

    if (currentTime >= endTime) { 
     System.out.println("Got it!"); 
     func(); 
    } 
} 

public void run() { 
    work(); 
} 

public void func() { 
    // function called when time matches 
} 
} 

我想停止的ScheduledThreadPoolExecutor當FUNC()被調用。沒有必要繼續努力!我想我應該把函數func()放在Voter類中,而不是創建某種回調。但也許我可以從Shoot課程中完成。

我該如何正確解決它?

+0

我並不都熟悉'ScheduledThreadPoolExecutor',但我的第一個猜測是'stpe.shutdown()'。你確實需要從'func()'獲得'stpe'。啓動在截止時間運行的第二個線程(計劃?)並調用shutdown()函數可能是合理的。 – Dorus

回答

20

ScheduledThreadPoolExecutor允許您立即執行您的任務或安排它稍後執行(您也可以設置定期執行)。

所以,如果你會使用這個類來阻止你的任務執行牢記這一點:

  1. 沒有辦法保證一個線程將停止對他的處決。檢查Thread.interrupt()文檔。
  2. 方法ScheduledThreadPoolExecutor.shutdown()將設置爲取消您的任務,它不會嘗試中斷您的線程。使用這種方法,您實際上可以避免執行較新的任務以及執行預定但未啓動的任務。
  3. ScheduledThreadPoolExecutor.shutdownNow()將中斷線程,但正如我在這個列表中的第一點說的方法...

當你要停止調度程序,您必須做這樣的事情:

//Cancel scheduled but not started task, and avoid new ones 
    myScheduler.shutdown(); 

    //Wait for the running tasks 
    myScheduler.awaitTermination(30, TimeUnit.SECONDS); 

    //Interrupt the threads and shutdown the scheduler 
    myScheduler.shutdownNow(); 

但是,如果您只需要停止一項任務呢?

方法ScheduledThreadPoolExecutor.schedule(...)返回一個ScheduleFuture,它表示您已經計劃好的任務。因此,您可以撥打ScheduleFuture.cancel(boolean mayInterruptIfRunning)方法取消您的任務,並在需要時嘗試中斷它。

+5

我只需要澄清一下上面的內容:爲什麼我們不能只做myScheduler.shutdownNow()?我擔心的任務等待結束可能需要任意時間。那麼爲什麼要去前兩行呢? – abksrv