同步包中的定時器
ScheduledExecutorService 利用線程池進行調度任務,內部使用一個DelayedWorkQueue實現,返回ScheduledFuture,而DelayQueue是用優先級隊列PriorityQueue實現的一個阻塞隊列,優先隊列的比較基準值是時間
private static class DelayedWorkQueue
extends AbstractCollection<Runnable>
implements BlockingQueue<Runnable> {
private final DelayQueue<ScheduledFutureTask> dq = new DelayQueue<ScheduledFutureTask>();
}
public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
implements BlockingQueue<E> {
private transient final ReentrantLock lock = new ReentrantLock();
private transient final Condition available = lock.newCondition();
private final PriorityQueue<E> q = new PriorityQueue<E>();
下面為一個小例:
public class ConcurrentTimer {
public static void main(String[] args) {
new ConcurrentTimer().getScheduledExecutorService();
}
public void getScheduledExecutorService() {
ScheduledExecutorService service = Executors.newScheduledThreadPool(10);
service.scheduleAtFixedRate(new Command(), 1, 1, TimeUnit.SECONDS);
}
public class Command implements Runnable {
public void run() {
System.out.println("Command");
}
}
}
posted on 2010-11-01 15:48 羔羊 閱讀(191) 評論(0) 編輯 收藏 所屬分類: concurrent