1. 程式人生 > >使用DelayQueue模擬一個超時的小場景,進行編碼!

使用DelayQueue模擬一個超時的小場景,進行編碼!

package com.bfxy.thread.core.mycollection;

import java.util.concurrent.DelayQueue;

/**
 * 模擬一個駕校學員簽到簽退的場景
 */
public class Jiaxiao implements Runnable{
    private DelayQueue<Xueyuan> dq = new DelayQueue<Xueyuan>();
    public boolean start = true;   //表示駕校在上課的時候

    public  void qiandao(Integer id, String name, Long time){
        Xueyuan xueyuan = new Xueyuan(id,name,time);
        dq.add(xueyuan);
        System.out.println(xueyuan.getName()+" 簽到");
    }
    public  void qiantui(Xueyuan xueyuan){
        System.out.println(xueyuan.getName()+" 時間已到,請簽退");
    }

    @Override
    public void run() {
        while (start){
            try {
                Xueyuan xueyuan = dq.take();
                qiantui(xueyuan);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static  void  main(String[] args){
        Jiaxiao jiaxiao = new Jiaxiao();
        Thread t1 = new Thread(jiaxiao);
        t1.start();
        try {
            jiaxiao.qiandao(1,"周鵬",System.currentTimeMillis());
            Thread.sleep(2000);
            jiaxiao.qiandao(2,"朱正興",System.currentTimeMillis());
            Thread.sleep(2000);
            jiaxiao.qiandao(3,"張新",System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

學員的實體類:

package com.bfxy.thread.core.mycollection;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class Xueyuan implements Delayed{
    public Integer id;
    public String name;
    public Long qiandaotime;

    public Xueyuan(Integer id, String name,Long qiandaotime) {
        this.id = id;
        this.name = name;
        this.qiandaotime = qiandaotime;
    }

    private final TimeUnit timeUnit = TimeUnit.SECONDS;

    private final int shangketime = 10000;//10s  延遲時間

    @Override
    public long getDelay(TimeUnit unit) {//需要實現的介面,獲得延遲時間   用過期時間-當前時間
        return (qiandaotime+shangketime)- System.currentTimeMillis();
    }

    @Override
    public int compareTo(Delayed o) {//用於延遲佇列內部比較排序   當前物件的延遲時間 - 比較物件的延遲時間
        Xueyuan xueyuan = (Xueyuan) o;
        return this.getDelay(timeUnit) - o.getDelay(timeUnit) > 0 ? 1 : 0;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Long getQiandaotime() {
        return qiandaotime;
    }

    public void setQiandaotime(Long qiandaotime) {
        this.qiandaotime = qiandaotime;
    }
}

執行結果: