[转]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;

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容