Java通过DelayQueue的实现多线程任务的阻塞队列

DelayQueue

1)java.util.concurrent.DelayQueue 延迟阻塞队列,是一个 有序的无界阻塞队列,只有在延迟期满时才能从中提取元素,该队列的头部为  延迟期满延迟到期时间最久 的Delayed元素;
放置入DelayQueue的元素必须实现Delayed接口;


2)实例代码,实现任务元素的延迟队列:
//定义延迟队列中的任务元素,可以通过extends实现不同的run方法;
class DelayedTask implements Runnable,Delayed{
     private final int delta;   //差值信号:用于记录任务线程的延迟时间;
     private final long trigger;    //触发信号:任务线程在加入队列,延迟期满,即将要执行时的系统时间;
     public DelayedTask(int delayInMilliseconds){
         delta = delayInMilliseconds;
         trigger = System.currentTimeMillis() + (long)delta;  
     }
     public long getDelay(TimeUnit unit){   //提供TimeUnit的时间单位的转换;
          return unit.convert(trigger - System.currentTimeMillis(),MILLISECONDS);
     }
     public void run(){
          ......
     }
}
//定义队列处理完所有的任务后,要执行的任务处理线程(永远在队列的末端,也可以更具需求不实现该类)
class static class EndSentinel extends DelayedTask{
     private ExecutorService exec;
     public EndSentinel(int delay,ExecutorService exec){
          super(delay);
          this.exec = exec;
     }
     public void run(){
          
          exec.shutdown();
     }
     
}

//定义使用整个延迟队列的任务类
class DelayedTaskConsumer implements Runnable{
     private DelayQueue queue;
     public DelayTaskConsumer(DelayQueue queue){ this.queue = queue; }
     public void run(){
          try{
               if(queue.size() == 0)
                    Thread.interrupt();
               while(!Thread.interrupted())
                    queue.take().run();
          }catch(InterruptedException ex){
          }
          
     }
}
//测试平台
class Driver{
     void main(){
          ExecutorService exec = Executors.newCachedThreadPool();
          DelayQueue queue = new DelayQueue();
          for(int i=0;i





你可能感兴趣的:(Java,Java,并发编程)