[轉]java 之DelayQueue實際運用示例

在學習Java 多線程并發開發過程中,了解到DelayQueue類的主要作用:是一個無界的BlockingQueue,用于放置實現了Delayed接口的對象,其中的對象只能在其到期時才能從隊列中取走。這種隊列是有序的,即隊頭對象的延遲到期時間最長。注意:不能將null元素放置到這種隊列中。

Delayed,一種混合風格的接口,用來標記那些應該在給定延遲時間之后執行的對象。此接口的實現必須定義一個compareTo方法,該方法提供與此接口的getDelay方法一致的排序。

在網上也看到兩個示例,但這兩個示例個人在實際運行時均沒有達到滿足業務場景的效果,因而對其進行了修改,供大家參考討論。

業務場景一:多考生考試

該場景來自于http://ideasforjava.iteye.com/blog/657384,模擬一個考試的日子,考試時間為120分鐘,30分鐘后才可交卷,當時間到了,或學生都交完卷了考試結束。

這個場景中幾個點需要注意:

考試時間為120分鐘,30分鐘后才可交卷,初始化考生完成試卷時間最小應為30分鐘

對于能夠在120分鐘內交卷的考生,如何實現這些考生交卷

對于120分鐘內沒有完成考試的考生,在120分鐘考試時間到后需要讓他們強制交卷

在所有的考生都交完卷后,需要將控制線程關閉

實現思想:用DelayQueue存儲考生(Student類),每一個考生都有自己的名字和完成試卷的時間,Teacher線程對DelayQueue進行監控,收取完成試卷小于120分鐘的學生的試卷。當考試時間120分鐘到時,先關閉Teacher線程,然后強制DelayQueue中還存在的考生交卷。每一個考生交卷都會進行一次countDownLatch.countDown(),當countDownLatch.await()不再阻塞說明所有考生都交完卷了,而后結束考試。

packagecom.my.base.concurrent.delayQueue;importjava.util.Iterator;importjava.util.Random;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.DelayQueue;importjava.util.concurrent.Delayed;importjava.util.concurrent.TimeUnit;/***this project is created for my partactice.

*In the? project I will write the mybatis by myself

*

*2014-1-10? 下午9:43:48

*@author孫振超? mychaoyue2011@163.com*/publicclassExam {/***

*2014-1-10 下午9:43:48 by 孫振超

*

*@paramargs

*void

*@throwsInterruptedException*/publicstaticvoidmain(String[] args)throwsInterruptedException {//TODO Auto-generated method stubintstudentNumber = 20;

CountDownLatch countDownLatch=newCountDownLatch(studentNumber+1);

DelayQueue< Student> students =newDelayQueue();

Random random=newRandom();for(inti = 0; i < studentNumber; i++) {

students.put(newStudent("student"+(i+1), 30+random.nextInt(120),countDownLatch));

}

Thread teacherThread=newThread(newTeacher(students));

students.put(newEndExam(students, 120,countDownLatch,teacherThread));

teacherThread.start();

countDownLatch.await();

System.out.println(" 考試時間到,全部交卷!");

}

}classStudentimplementsRunnable,Delayed{privateString name;privatelongworkTime;privatelongsubmitTime;privatebooleanisForce =false;privateCountDownLatch countDownLatch;publicStudent(){}publicStudent(String name,longworkTime,CountDownLatch countDownLatch){this.name =name;this.workTime =workTime;this.submitTime = TimeUnit.NANOSECONDS.convert(workTime, TimeUnit.NANOSECONDS)+System.nanoTime();this.countDownLatch =countDownLatch;

}

@OverridepublicintcompareTo(Delayed o) {//TODO Auto-generated method stubif(o ==null|| ! (oinstanceofStudent))return1;if(o ==this)return0;

Student s=(Student)o;if(this.workTime >s.workTime) {return1;

}elseif(this.workTime ==s.workTime) {return0;

}else{return-1;

}

}

@OverridepubliclonggetDelay(TimeUnit unit) {//TODO Auto-generated method stubreturnunit.convert(submitTime -System.nanoTime(),? TimeUnit.NANOSECONDS);

}

@Overridepublicvoidrun() {//TODO Auto-generated method stubif(isForce) {

System.out.println(name+ " 交卷, 希望用時" + workTime + "分鐘"+" ,實際用時 120分鐘");

}else{

System.out.println(name+ " 交卷, 希望用時" + workTime + "分鐘"+" ,實際用時 "+workTime +" 分鐘");

}

countDownLatch.countDown();

}publicbooleanisForce() {returnisForce;

}publicvoidsetForce(booleanisForce) {this.isForce =isForce;

}

}classEndExamextendsStudent{privateDelayQueuestudents;privateCountDownLatch countDownLatch;privateThread teacherThread;publicEndExam(DelayQueue students,longworkTime, CountDownLatch countDownLatch,Thread teacherThread) {super("強制收卷", workTime,countDownLatch);this.students =students;this.countDownLatch =countDownLatch;this.teacherThread =teacherThread;

}

@Overridepublicvoidrun() {//TODO Auto-generated method stubteacherThread.interrupt();

Student tmpStudent;for(Iterator iterator2 =students.iterator(); iterator2.hasNext();) {

tmpStudent=iterator2.next();

tmpStudent.setForce(true);

tmpStudent.run();

}

countDownLatch.countDown();

}

}classTeacherimplementsRunnable{privateDelayQueuestudents;publicTeacher(DelayQueuestudents){this.students =students;

}

@Overridepublicvoidrun() {//TODO Auto-generated method stubtry{

System.out.println(" test start");while(!Thread.interrupted()){

students.take().run();

}

}catch(Exception e) {//TODO: handle exceptione.printStackTrace();

}

}

}

業務場景二:具有過期時間的緩存

該場景來自于http://www.cnblogs.com/jobs/archive/2007/04/27/730255.html,向緩存添加內容時,給每一個key設定過期時間,系統自動將超過過期時間的key清除。

這個場景中幾個點需要注意:

當向緩存中添加key-value對時,如果這個key在緩存中存在并且還沒有過期,需要用這個key對應的新過期時間

為了能夠讓DelayQueue將其已保存的key刪除,需要重寫實現Delayed接口添加到DelayQueue的DelayedItem的hashCode函數和equals函數

當緩存關閉,監控程序也應關閉,因而監控線程應當用守護線程

具體實現如下:

packagecom.my.base.concurrent.delayQueue;importjava.util.Random;importjava.util.concurrent.ConcurrentHashMap;importjava.util.concurrent.DelayQueue;importjava.util.concurrent.Delayed;importjava.util.concurrent.TimeUnit;/***Cache.java

*

* Created on 2014-1-11 上午11:30:36 by sunzhenchao mychaoyue2011@163.com*/publicclassCache{publicConcurrentHashMap map =newConcurrentHashMap();publicDelayQueue> queue =newDelayQueue>();publicvoidput(K k,V v,longliveTime){

V v2=map.put(k, v);

DelayedItem tmpItem =newDelayedItem(k, liveTime);if(v2 !=null) {

queue.remove(tmpItem);

}

queue.put(tmpItem);

}publicCache(){

Thread t=newThread(){

@Overridepublicvoidrun(){

dameonCheckOverdueKey();

}

};

t.setDaemon(true);

t.start();

}publicvoiddameonCheckOverdueKey(){while(true) {

DelayedItem delayedItem =queue.poll();if(delayedItem !=null) {

map.remove(delayedItem.getT());

System.out.println(System.nanoTime()+" remove "+delayedItem.getT() +" from cache");

}try{

Thread.sleep(300);

}catch(Exception e) {//TODO: handle exception}

}

}/*** TODO

*@paramargs

* 2014-1-11 上午11:30:36

*@author:孫振超

*@throwsInterruptedException*/publicstaticvoidmain(String[] args)throwsInterruptedException {

Random random=newRandom();intcacheNumber = 10;intliveTime = 0;

Cache cache =newCache();for(inti = 0; i < cacheNumber; i++) {

liveTime= random.nextInt(3000);

System.out.println(i+"? "+liveTime);

cache.put(i+"", i, random.nextInt(liveTime));if(random.nextInt(cacheNumber) > 7) {

liveTime= random.nextInt(3000);

System.out.println(i+"? "+liveTime);

cache.put(i+"", i, random.nextInt(liveTime));

}

}

Thread.sleep(3000);

System.out.println();

}

}classDelayedItemimplementsDelayed{privateT t;privatelongliveTime ;privatelongremoveTime;publicDelayedItem(T t,longliveTime){this.setT(t);this.liveTime =liveTime;this.removeTime = TimeUnit.NANOSECONDS.convert(liveTime, TimeUnit.NANOSECONDS) +System.nanoTime();

}

@OverridepublicintcompareTo(Delayed o) {if(o ==null)return1;if(o ==this)return0;if(oinstanceofDelayedItem){

DelayedItem tmpDelayedItem = (DelayedItem)o;if(liveTime >tmpDelayedItem.liveTime ) {return1;

}elseif(liveTime ==tmpDelayedItem.liveTime) {return0;

}else{return-1;

}

}longdiff = getDelay(TimeUnit.NANOSECONDS) -o.getDelay(TimeUnit.NANOSECONDS);returndiff > 0 ? 1:diff == 0? 0:-1;

}

@OverridepubliclonggetDelay(TimeUnit unit) {returnunit.convert(removeTime -System.nanoTime(), unit);

}publicT getT() {returnt;

}publicvoidsetT(T t) {this.t =t;

}

@OverridepublicinthashCode(){returnt.hashCode();

}

@Overridepublicbooleanequals(Object object){if(objectinstanceofDelayedItem) {returnobject.hashCode() == hashCode() ?true:false;

}returnfalse;

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容