用Java的延時隊列,實作顧客到了點就自動下機。
所謂延時隊列,就是不到固定要求,不能從裡面取值,即便取值,取值也為null。
對比其他隊列:
SynchronousQueue 隊列不能存放資料,存放資料就報錯,但是可以先開一個線程持續從其中取值,另一個線程放資料
LinkedBlockingQueue 阻塞有界隊列,如果不指定大小,可存放多個值
ArrayBlockingQueue 阻塞無界隊列,必須指定大小,超過添加就報錯
ConcurrentLinkedQueue 高性能無阻塞無界隊列
PriorityBlockingQueue 優先級隊列,存放值時不排序,取值時開始排序
DelayQueue 延時無界隊列,隻有到了設定的條件下才能取值
package cn.base;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* @Description : 需要放入延時隊列的對象,需要實作Delayed接口
* @Author : 小書包
* @CreateDate :2018-11-23 18:03
*/
public class Person implements Delayed{
// 使用者名
private String name;
// 身份證号
private int id;
// 上機金額
private int money;
// 結束時間
private long endTime;
// 配置目前計算的時間機關,毫秒
private TimeUnit timeUnit = TimeUnit.MILLISECONDS;
public Person(String name, int id, int money) {
this.name = name;
this.id = id;
this.endTime = money * 1000 + System.currentTimeMillis();
}
/**
* 結束時間與目前時間進行比較,傳回結果
* @param unit
* @return
*/
@Override
public long getDelay(TimeUnit unit) {
return endTime - System.currentTimeMillis();
}
/**
* 判斷是否可以取出
* @param o
* @return
*/
@Override
public int compareTo(Delayed o) {
Person person = (Person) o;
return (int) (this.getDelay(this.timeUnit) - person.getDelay(this.timeUnit));
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
package cn.base;
import java.util.concurrent.DelayQueue;
/**
* @Description : 需要實作Runnable接口
* @Author : 小書包
* @CreateDate :2018-11-23 18:09
*/
public class NetBar implements Runnable {
// 是否正常營業
private volatile boolean isRun = true;
// 延時隊列
private DelayQueue<Person> queue = new DelayQueue<>();
/**
* 顧客上機
* @param person
*/
void surfNet(Person person){
System.out.println("顧客:"+person.getName()+" 身份證号:"+person.getId()+"交錢:"+person.getMoney()+"塊,開始上機...");
queue.offer(person);
}
/**
* 顧客下機
* @param person
*/
void offlineNet(Person person){
System.out.println("顧客:"+person.getName()+" 身份證号:"+person.getId()+"時間已到,開始下機...");
}
@Override
public void run() {
while (isRun) {
try {
// 持續擷取,如果擷取不到則将繼續擷取
Person person = queue.take();
// 獲得人員之後,開始讓他下線
offlineNet(person);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
NetBar netBar = new NetBar();
System.out.println("網吧開始營業");
new Thread(netBar).start();
netBar.surfNet(new Person("張三",2,4));
netBar.surfNet(new Person("李四",2,4));
netBar.surfNet(new Person("王五",2,4));
netBar.surfNet(new Person("路六",2,4));
}
}
網吧開始營業
顧客:張三 身份證号:2交錢:0塊,開始上機...
顧客:李四 身份證号:2交錢:0塊,開始上機...
顧客:王五 身份證号:2交錢:0塊,開始上機...
顧客:路六 身份證号:2交錢:0塊,開始上機...
=============
顧客:張三 身份證号:2時間已到,開始下機...
顧客:路六 身份證号:2時間已到,開始下機...
顧客:王五 身份證号:2時間已到,開始下機...
顧客:李四 身份證号:2時間已到,開始下機...