您现在的位置:首页 >> 基础 >> Java编程 >> 内容

多线程DelayQueue的使用----延期队列(具有优先队列的特性)--Java学习网

时间:2016-8-1 12:30:25

  核心提示:import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent...
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
/**
 * 创建了20个延期时长不同的延期任务,用于观看延期任务在延期队列中的排序情况
 */
public class DelayQueueDemo {
  public static void main(String[] args) {
    Random random = new Random(47);
    ExecutorService exec = Executors.newCachedThreadPool();
    DelayQueue<DelayedTask> queue = new DelayQueue<>();
    for (int i = 0; i < 20; i++) {
      queue.put(new DelayedTask(random.nextInt(5000)));
    }
    queue.add(new DelayedTask.EndSentinel(5000, exec));
    exec.execute(new DelayedTaskConsumer(queue));
  }
}
 
class DelayedTask implements Runnable, Delayed {
  private static int counter = 0;
  private final int id = counter++;
  private final int delta;
  private final long trigger;
  protected static List<DelayedTask> sequence = new ArrayList<>();
 
  public DelayedTask(int delayInMilliseconds) {
    delta = delayInMilliseconds;
    trigger = System.nanoTime() + TimeUnit.NANOSECONDS.convert(delta, TimeUnit.MICROSECONDS);
    sequence.add(this);
  }
 
  /**
   * 获取当前延迟任务还剩下多少延期的时长
   * @param unit
   * @return
   */
  @Override
  public long getDelay(TimeUnit unit) {
    return unit.convert(trigger - System.nanoTime(), TimeUnit.NANOSECONDS);
  }
 
  /**
   * 用于对延期任务进行排序,这里的排序方式是按延期时长的从小到大排的,也即
   * 从队列中取出时是以从小到大的顺序取出的
   * @param o
   * @return
   */
  @Override
  public int compareTo(Delayed o) {
    DelayedTask that = (DelayedTask) o;
    if (trigger < that.trigger) {
      return -1;
    }
    if (trigger > that.trigger) {
      return 1;
    }
    return 0;
  }
 
  @Override
  public void run() {
    System.out.print(this + " ");
  }
 
  @Override
  public String toString() {
    return String.format("[%1$-4d]", delta) + " Task " + id;
  }
 
  public String summary() {
    return "(" + id + ": " + delta + ")";
  }
 
  public static class EndSentinel extends DelayedTask {
    private ExecutorService exec;
 
    public EndSentinel(int delay, ExecutorService exec) {
      super(delay);
      this.exec = exec;
    }
 
    @Override
    public v, oid run() {
      sequence.forEach(pt -> System.out.print(pt.summary() + " "));
      System.out.println();
      System.out.println(this + " Calling shutdownNow()");
      exec.shutdownNow();
    }
  }
}
 
class DelayedTaskConsumer implements Runnable {
  private DelayQueue<DelayedTask> queue;
 
  public DelayedTaskConsumer(DelayQueue<DelayedTask> queue) {
    this.queue = queue;
  }
 
  @Override
  public void run() {
    try {
      while (!Thread.interrupted()) {
        queue.take().run();
      }
    } catch (InterruptedException e) {}
    System.out.println("Finished DelayedTaskConsumer");
  }
}

Java免费学习   Java自学网 http://www.javalearns.com

关注微信号:javalearns   随时随地学Java

或扫一扫

随时随地学Java

作者:不详 来源:网络
    你是从哪里知道本网站的?
  • 网友介绍的
  • 百度搜索的
  • Google搜索的
  • 其它搜索过来的
  • 网址输错了进来的
  • 太忙了不记得了
共有评论 0相关评论
发表我的评论
  • 大名:
  • 内容:
  • java学习网(www.javalearns.com) © 2014 版权所有 All Rights Reserved.
  • Email:javalearns@163.com 站长QQ:1356121699 晋ICP备14003680号-3
  • java学习网部分内容来自网络或网友发布,如侵犯了您利益,请发邮件至:javalearns@126.com,我们尽快处理!
  • Java学习网
  • 网站统计
  • 晋公网安备 14042902000001号