ScheduledThreadPoolExecutor,如何停止runnable类JAVA

Kho*_*zzy 9 java runnable

我写了以下代码:

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
}
}
Run Code Online (Sandbox Code Playgroud)

我想在调用func()时停止ScheduledThreadPoolExecutor.它没有必要进一步工作!我想我应该把函数func()放在Voter类中,而不是创建某种回调.但也许我可以在Shoot课程中做到这一点.

我怎样才能正确解决?

gga*_*iao 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();
Run Code Online (Sandbox Code Playgroud)

但是如果你只需要停止一项任务呢?

该方法ScheduledThreadPoolExecutor.schedule(...)返回一个ScheduleFuture表示已计划任务的表示.因此,您可以调用该ScheduleFuture.cancel(boolean mayInterruptIfRunning)方法取消您的任务,并尝试在需要时中断它.

  • 我只需要对上述内容进行一次澄清:为什么我们不能只执行myScheduler.shutdownNow()?我关心的是等待任务完成的终止可能需要任意时间.那么为什么选择前两行呢? (5认同)