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
}
}

我想在调用func()时停止ScheduledThreadPoolExecutor。无需进一步工作!我认为我应该将功能func()放在Voter类中,而不是创建某种回调。但是也许我可以在Shoot类中做到这一点。

我该如何正确解决?

加西亚奥:

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)方法来取消任务,并在需要时尝试中断它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章