java.util.concurrent.scheduledthreadpoolexecutor
是threadpoolexecutor
的子类,并且可以额外地调度在给定延迟之后运行的命令,或定期执行。
以下testthread
程序显示了基于线程的环境中scheduledthreadpoolexecutor
接口的使用。
import java.util.concurrent.executors;
import java.util.concurrent.scheduledthreadpoolexecutor;
import java.util.concurrent.scheduledfuture;
import java.util.concurrent.timeunit;
public class testthread {
public static void main(final string[] arguments) throws interruptedexception {
final scheduledthreadpoolexecutor scheduler = (scheduledthreadpoolexecutor)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