我寫了下面的代碼:的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課程中完成。
我該如何正確解決它?
我並不都熟悉'ScheduledThreadPoolExecutor',但我的第一個猜測是'stpe.shutdown()'。你確實需要從'func()'獲得'stpe'。啓動在截止時間運行的第二個線程(計劃?)並調用shutdown()函數可能是合理的。 – Dorus