Java ScheduledThreadPoolExecutor类
1 ScheduledThreadPoolExecutor接口的介绍
java.util.concurrent.ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类,并且可以额外地调度在给定延迟之后运行的命令,或定期执行。
2 ScheduledThreadPoolExecutor接口的案例
以下TestThread程序显示了基于线程的环境中ScheduledThreadPoolExecutor接口的使用。
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
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
热门文章
优秀文章