Java - 延迟队列

Task.java

public class Task<T extends Runnable> implements Delayed {
  // 到期时间
  private final long time;
  // 任务
  private final T task;
  // 用于标识当前任务
  private final long n;
  private final AtomicLong atomic = new AtomicLong(0);

  public Task(long timeout, T task) {
    this.time = System.nanoTime() + timeout;
    this.task = task;
    this.n = atomic.getAndIncrement();
  }

  @Override
  public int compareTo(Delayed o) {
    if (o == this)
      return 0;
    if (o instanceof Task) {
      Task<?> x = (Task<?>) o;
      long diff = time - x.time;
      if (diff < 0)
        return -1;
      else if (diff > 0)
        return 1;
      else if (n < x.n)
        return -1;
      else
        return 1;
    }
    long d = (getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS));
    return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
  }

  /**
   * 返回与此对象相关的剩余延迟时间,以给定的时间单位表示
   */
  @Override
  public long getDelay(TimeUnit unit) {
    return unit.convert(this.time - System.nanoTime(), TimeUnit.NANOSECONDS);
  }

  public T getTask() {
    return task;
  }

  @Override
  public int hashCode() {
    return task.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    if (obj instanceof Task) {
      return obj.hashCode() == hashCode() ? true : false;
    }
    return false;
  }

}

TaskQueueThread.java

public class TaskQueueThread {

  private TaskQueueThread() {
  }

  private static class LazyHolder {
    private final static TaskQueueThread instance = new TaskQueueThread();
    static {
      //首次调用 ItemQueueThread.getInstance() 的时候进行初始化 thread
      instance.init();
    }
  }

  public static TaskQueueThread getInstance() {
    return LazyHolder.instance;
  }

  private Executor executor = Executors.newFixedThreadPool(10);

  private DelayQueue<Task<?>> queue = new DelayQueue<>();

  private Thread daemonThread;

  public void init() {
    daemonThread = new Thread(() -> execute());
    daemonThread.start();
  }

  private void execute() {
    System.out.println("current time -> "+ System.currentTimeMillis());
    while (true) {
      try {
        // 从延迟队列中取值,如果没有对象过期则队列一直等待,
        Task<?> t1 = (Task<?>) queue.take();
        if (t1 != null) {
          // 修改问题的状态
          Runnable task = t1.getTask();
          if (task != null) {
            executor.execute(task);
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
        break;
      }
    }
  }

  /**
   * 添加任务
   * @param time
   * @param task
   */
  public void put(long time, Runnable task) {
    // 转换成ns
    long nanoTime = TimeUnit.NANOSECONDS.convert(time, TimeUnit.MILLISECONDS);
    // 创建一个任务
    Task<?> k = new Task<>(nanoTime, task);
    // 将任务放在延迟的队列中
    queue.put(k);
  }

  /**
   * 结束任务
   * @param task
   */
  public boolean endTask(Task<Runnable> task) {
    return queue.remove(task);
  }

}

TaskInfo.java

public class TaskInfo implements Cloneable {

  private String id;
  private String name;
  private String color;

  public TaskInfo() {
    this.id = UUID.randomUUID().toString();
  }

  public TaskInfo(String name, String color) {
    this.id = UUID.randomUUID().toString();
    this.name = name;
    this.color = color;
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getColor() {
    return color;
  }

  public void setColor(String color) {
    this.color = color;
  }

  @Override
  public String toString() {
    return "{id:" + id + ",name:" + name + ",color:" + color + "}";
  }

}

TaskRun.java

public class TaskRun implements Runnable {

  private TaskInfo taskInfo;

  public TaskRun(TaskInfo taskInfo) {
    this.taskInfo = taskInfo;
  }

  @Override
  public void run() {
    System.out.println(taskInfo);
  }

}

TaskTest.java

public class TaskTest {

  public static void main(String[] args) throws Exception {

    TaskQueueThread tq = TaskQueueThread.getInstance();
    for (int i = 1; i <= 5; i++) {
      tq.put(1000 * i, new TaskRun(new TaskInfo("name" + i, "color" + i)));
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值