yuyee

同步包中的定时器

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 羔羊 阅读(180) 评论(0)  编辑  收藏 所属分类: concurrent