我写了以下代码:
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
}
}
我想在调用 func() 时停止 ScheduledThreadPoolExecutor。没有必要让它继续工作!我认为我应该将函数 func() 放在 Voter 类中,然后创建某种回调。但也许我可以在 Shoot 类中做到这一点。
我怎样才能正确解决它?