java.util.concurrent.scheduledexecutorservice
接口是executorservice
接口的子接口,并支持将来和/或定期执行任务。
序号 | 方法 | 描述 |
---|---|---|
1 | scheduledfuture schedule(callable callable, long delay, timeunit unit) |
创建并执行在给定延迟后启用scheduledfuture 。 |
2 | scheduledfuture<?> schedule(runnable command, long delay, timeunit unit) |
创建并执行在给定延迟后启用的单次操作。 |
3 | scheduledfuture<?> scheduleatfixedrate(runnable command, long initialdelay, long period, timeunit unit) |
创建并执行在给定的初始延迟之后,随后以给定的时间段首先启用的周期性动作; 那就是执行会在initialdelay 之后开始,然后是initialdelay + period ,然后是initialdelay + 2 * period ,等等。 |
4 | scheduledfuture<?> schedulewithfixeddelay(runnable command, long initialdelay, long delay, timeunit unit) |
创建并执行在给定的初始延迟之后首先启用的定期动作,随后在一个执行的终止和下一个执行的开始之间给定的延迟。 |
以下testthread
程序显示了基于线程的环境中scheduledexecutorservice
接口的使用。
import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.scheduledfuture;
import java.util.concurrent.timeunit;
public class testthread {
public static void main(final string[] arguments) throws interruptedexception {
final scheduledexecutorservice scheduler = executors.newscheduledthreadpool(1);
final scheduledfuture<?> beephandler =
scheduler.scheduleatfixedrate(new beeptask(), 2, 2, timeunit.seconds);
scheduler.schedule(new runnable() {
@override
public void run() {
beephandler.cancel(true);
scheduler.shutdown();
}
}, 10, timeunit.seconds);
}
static class beeptask implements runnable {
public void run() {
system.out.println("beep");
}
}
}
这将产生以下结果 -
beep
beep
beep
beep
beep