java延遲隊列

來源:互聯網
上載者:User

標籤:...   子類   處理   ++   訂單   介面   else   start   支付   

大多數用到定時執行的功能都是用任務調度來做的,單身當碰到類似訂餐業務/購物等這種業務就不好處理了,比如購物的訂單功能,在你的訂單管理中

有N個訂單,當訂單超過十分鐘未支付的時候自動釋放購物車中的商品,訂單失效。這種高頻率的延遲任務再用任務調度(定時)實現就得不償失了。推薦用Java延遲隊列來實現,DelayQueue是java.util.concurrent中提供的一個類DelayQueue是一個無界的BlockingQueue,用於放置實現了Delayed介面的對象,

其中的對象只能在其到期時才能從隊列中中取走。這種隊列是有序的,即對頭對象的延遲到期時間最長。注意:不能講null元素放置到這種隊列中。

import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicLong;//任務線程 實現delayed介面public class DelayItem<T extends Runnable> implements Delayed {//到期時間private final long time;//任務對象private final T task;//原子類private static final AtomicLong atomic = new AtomicLong(0);private final long n;public DelayItem(long timeout, T t) {    this.time = Systen,nanoTime() + timeout;    this.task = t;    this.n = atomic.getAndIncrement();}//返回與此對象相關的剩餘延遲時間,以給定的時間單位表示public long getDelay(TimeUnit unit) {    return unit.convert(this.time - System.nanoTime(),TimeUnit.NANOSECONDS);}public int compareTo(Delayed other) {    if(other == this) {    return 0;    }    if(other instanceof DelayItem) {        DelayItem<?> x = (DelayItem<?>)other;        long diff = tiem - 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) -           other.getDelay(TimeUnit.NANOSECONDS));        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);    }    public T getTask(){        return this.task;    }    @Override    public int hashCode(){        return task.hashCode();    }    @Override    public boolean equals(Object object){        if(object instanceof DelayItem){            return object.hashCode() == hashCode() ? true : false;    }    return false;}}//管理延遲任務的類import java.util.Map;import java.util.concurrent.DelayQueue;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import org.apache.log4j.Logger;//延遲隊列存放有效期間對象public class ItemQueueThread {private static final Logger logger = Logger.getLogger(this.class);private ItemQueueThread(){}//消極式載入(安全執行緒)private static class LazyHolder{    private static ItemQueueThread itemQueueThread = new ItemQueueThread();}public static ItemQueueThread getInstance(){    return LazyHolder.itemQueueThread;}//緩衝線程池ExecutorService executor = Executors.newCacheThreadPool();//線程private Thread daemonThead;//初始化線程public void init() {    daemonThread = new Thread(() -> {        try{            execute();        }cathc(InterruptedException e){            e.printStackTrace();            logger.info(e.getMessage());        }    });    System.out.println("init......start");    daemonThread.start();}private void execute() throws InterrupedException {    while(true) {        Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();        System.out.println("線程數...." + map.size());        System.out.println(System.currentTimeMills());        System.out.println(item.size());        System.out.println("線程狀態----" + Thread.currentThread().getState());        try{            //從延遲隊列中取值,如果沒有對象到期責隊列一直等待            DelayItem<?> t1 = item.take();            if(t1 != null){                Runnable task = t1.getTask();                    if(task == null){                        continue;                }                executor.execute(task);            }        }catch(Exception e) {            e.printStackTrace();            logger.info(e.getMessage());        }    }}//建立空的延遲隊列private DelayQueue<DelayItem<?>> item = new DelayQueue<>();//往隊列中新增工作public void put(long time, Runnable task, TimeUnit timeUnit){    //轉換成ns    long nanoTime = TimeUnit.NANOSECONDS.convert(time,timeUnit);    DelayItem<?> k = new DelayItem(nanoTime,task);    item.put(k);_:}//結束任務public boolean endTask(DelayItem<Runnable> task){    return item.remove(task);}}//把需要延遲的功能代碼單獨抽取出來作為一個類,繼承Runnable實現run方法public class DataDemo implements Runnable {    int a = -1;    public DataDemo(int i){        this.a = i;}@Overridepublic void run(){    System.out.println("逾時,要撤銷訂單...." + a);}}//test classimport java.util.Random;import java.util.concurrent.TimeUnit;public class DelayTest{public static void main(String[] args){    ItemQueueThread  ith = ItemQueueThread.getInstance();    ith.init();    Random r = new Random();    for(int i = 0; i < 5; i++){        int a = r.nextInt(20);        System.out.println("預Crowdsourced Security Testing道等待時間:" + a);        DataDemo dd = new DataDemo(a);//建立一個任務對象        ith.put(a,dd,TimeUnit.SECONDS);//將任務添加到隊列中    }}}//注意ItemQueueThread的init方法,要在容器初始化的時候就要執行,或在第一次put延遲物件任務之前就要初始化完成,當設定的延遲時間到期時會執行任務對象中的run}            

  

java延遲隊列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.