ScheduledExecutorService在使用schedule提交定时任务时会返回一个ScheduledFuture>,可以调用它的cancel方法。
代码如下。
import org.junit.Test;
import java.util.concurrent.*;
/**
* Created by fanxian
* datetime on 2017/11/11 16:41.
*/
public class ScheduledExecutorServiceTest {
@Test
public void t1() throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
System.out.println("创建5秒延迟的任务");
ScheduledFuture> schedule = scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
doTask("5s");
}
}, 5, TimeUnit.SECONDS);
Thread.sleep(4900);
schedule.cancel(false);
System.err.println("取消5秒延迟的任务");
System.out.println();
System.out.println("创建3秒延迟的任务");
ScheduledFuture> schedule2 = scheduledExecutorService.schedule(new Runnable() {
@Override
public void run() {
doTask("3s");
}
}, 3, TimeUnit.SECONDS);
Thread.sleep(4000);
}
private void doTask(String arg) {
System.out.println(arg + " 任务执行 ");
}
}