好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java延迟队列原理与用法实例详解

本文实例讲述了java 延迟队列 原理与用法。分享给大家供大家参考,具体如下:

延时队列,第一他是个队列,所以具有对列功能第二就是延时,这就是延时对列,功能也就是将任务放在该延时对列中,只有到了延时时刻才能从该延时对列中获取任务否则获取不到……

应用场景比较多,比如延时1分钟发短信,延时1分钟再次执行等,下面先看看延时队列demo之后再看延时队列在项目中的使用:

简单的延时队列要有三部分:第一实现了delayed接口的消息体、第二消费消息的消费者、第三存放消息的延时队列,那下面就来看看延时队列demo。

一、消息体

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

package com.delqueue;

import java.util.concurrent.delayed;

import java.util.concurrent.timeunit;

/**

  * 消息体定义 实现delayed接口就是实现两个方法即compareto 和 getdelay最重要的就是getdelay方法,这个方法用来判断是否到期……

  *

  * @author whd

  * @date 2017年9月24日 下午8:57:14

  */

public class message implements delayed {

     private int id;

     private string body; // 消息内容

     private long excutetime; // 延迟时长,这个是必须的属性因为要按照这个判断延时时长。

     public int getid() {

         return id;

     }

     public string getbody() {

         return body;

     }

     public long getexcutetime() {

         return excutetime;

     }

     public message( int id, string body, long delaytime) {

         this .id = id;

         this .body = body;

         this .excutetime = timeunit.nanoseconds.convert(delaytime, timeunit.milliseconds) + system.nanotime();

     }

     // 自定义实现比较方法返回 1 0 -1三个参数

     @override

     public int compareto(delayed delayed) {

         message msg = (message) delayed;

         return integer.valueof( this .id) > integer.valueof(msg.id) ? 1

                 : (integer.valueof( this .id) < integer.valueof(msg.id) ? - 1 : 0 );

     }

     // 延迟任务是否到时就是按照这个方法判断如果返回的是负数则说明到期否则还没到期

     @override

     public long getdelay(timeunit unit) {

         return unit.convert( this .excutetime - system.nanotime(), timeunit.nanoseconds);

     }

}

二、消息消费者

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package com.delqueue;

import java.util.concurrent.delayqueue;

public class consumer implements runnable {

     // 延时队列 ,消费者从其中获取消息进行消费

     private delayqueue<message> queue;

     public consumer(delayqueue<message> queue) {

         this .queue = queue;

     }

     @override

     public void run() {

         while ( true ) {

             try {

                 message take = queue.take();

                 system.out.println( "消费消息id:" + take.getid() + " 消息体:" + take.getbody());

             } catch (interruptedexception e) {

                 e.printstacktrace();

             }

         }

     }

}

三、延时队列

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package com.delqueue;

import java.util.concurrent.delayqueue;

import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

public class delayqueuetest {

      public static void main(string[] args) {

         // 创建延时队列

         delayqueue<message> queue = new delayqueue<message>();

         // 添加延时消息,m1 延时3s

         message m1 = new message( 1 , "world" , 3000 );

         // 添加延时消息,m2 延时10s

         message m2 = new message( 2 , "hello" , 10000 );

         //将延时消息放到延时队列中

         queue.offer(m2);

         queue.offer(m1);

         // 启动消费线程 消费添加到延时队列中的消息,前提是任务到了延期时间

         executorservice exec = executors.newfixedthreadpool( 1 );

         exec.execute( new consumer(queue));

         exec.shutdown();

       }

}

将消息体放入延迟队列中,在启动消费者线程去消费延迟队列中的消息,如果延迟队列中的消息到了延迟时间则可以从中取出消息否则无法取出消息也就无法消费。

这就是延迟队列demo,下面我们来说说在真实环境下的使用。

使用场景描述:

在打车软件中对订单进行派单的流程,当有订单的时候给该订单筛选司机,然后给当订单绑定司机,但是有时运气没那么好,订单进来后第一次没有筛选到合适的司机,但我们也不能就此结束派单,而是将该订单的信息放到延时队列中过个2秒钟在进行一次,其实这个2秒钟就是一个延迟,所以这里我们就可以使用延时队列来实现……

下面看看简单的流程图:

下面来看看具体代码实现:

在项目中有如下几个类:第一 、任务类   第二、按照任务类组装的消息体类  第三、延迟队列管理类

任务类即执行筛选司机、绑单、push消息的任务类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

package com.test.delayqueue;

/**

  * 具体执行相关业务的业务类

  * @author whd

  * @date 2017年9月25日 上午12:49:32

  */

public class delayorderworker implements runnable {

     @override

     public void run() {

         // todo auto-generated method stub

         //相关业务逻辑处理

         system.out.println(thread.currentthread().getname()+ " do something ……" );

     }

}

消息体类,在延时队列中这个实现了delayed接口的消息类是比不可少的,实现接口时有一个getdelay(timeunit unit)方法,这个方法就是判断是否到期的

这里定义的是一个泛型类,所以可以将我们上面的任务类作为其中的task,这样就将任务类分装成了一个消息体

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

package com.test.delayqueue;

import java.util.concurrent.delayed;

import java.util.concurrent.timeunit;

/**

  * 延时队列中的消息体将任务封装为消息体

  *

  * @author whd

  * @date 2017年9月25日 上午12:48:30

  * @param <t>

  */

public class delayordertask<t extends runnable> implements delayed {

     private final long time;

     private final t task; // 任务类,也就是之前定义的任务类

     /**

      * @param timeout

      *      超时时间(秒)

      * @param task

      *      任务

      */

     public delayordertask( long timeout, t task) {

         this .time = system.nanotime() + timeout;

         this .task = task;

     }

     @override

     public int compareto(delayed o) {

         // todo auto-generated method stub

         delayordertask other = (delayordertask) o;

         long diff = time - other.time;

         if (diff > 0 ) {

             return 1 ;

         } else if (diff < 0 ) {

             return - 1 ;

         } else {

             return 0 ;

         }

     }

     @override

     public long getdelay(timeunit unit) {

         // todo auto-generated method stub

         return unit.convert( this .time - system.nanotime(), timeunit.nanoseconds);

     }

     @override

     public int hashcode() {

         return task.hashcode();

     }

     public t gettask() {

         return task;

     }

}

延时队列管理类,这个类主要就是将任务类封装成消息并并添加到延时队列中,以及轮询延时队列从中取出到时的消息体,在获取任务类放到线程池中执行任务

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

package com.test.delayqueue;

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 java.util.concurrent.atomic.atomiclong;

/**

  * 延时队列管理类,用来添加任务、执行任务

  *

  * @author whd

  * @date 2017年9月25日 上午12:44:59

  */

public class delayorderqueuemanager {

     private final static int default_thread_num = 5 ;

     private static int thread_num = default_thread_num;

     // 固定大小线程池

     private executorservice executor;

     // 守护线程

     private thread daemonthread;

     // 延时队列

     private delayqueue<delayordertask<?>> delayqueue;

     private static final atomiclong atomic = new atomiclong( 0 );

     private final long n = 1 ;

     private static delayorderqueuemanager instance = new delayorderqueuemanager();

     private delayorderqueuemanager() {

         executor = executors.newfixedthreadpool(thread_num);

         delayqueue = new delayqueue<>();

         init();

     }

     public static delayorderqueuemanager getinstance() {

         return instance;

     }

     /**

      * 初始化

      */

     public void init() {

         daemonthread = new thread(() -> {

             execute();

         });

         daemonthread.setname( "delayqueuemonitor" );

         daemonthread.start();

     }

     private void execute() {

         while ( true ) {

             map<thread, stacktraceelement[]> map = thread.getallstacktraces();

             system.out.println( "当前存活线程数量:" + map.size());

             int tasknum = delayqueue.size();

             system.out.println( "当前延时任务数量:" + tasknum);

             try {

                 // 从延时队列中获取任务

                 delayordertask<?> delayordertask = delayqueue.take();

                 if (delayordertask != null ) {

                     runnable task = delayordertask.gettask();

                     if ( null == task) {

                         continue ;

                     }

                     // 提交到线程池执行task

                     executor.execute(task);

                 }

             } catch (exception e) {

                 e.printstacktrace();

             }

         }

     }

     /**

      * 添加任务

      *

      * @param task

      * @param time

      *      延时时间

      * @param unit

      *      时间单位

      */

     public void put(runnable task, long time, timeunit unit) {

         // 获取延时时间

         long timeout = timeunit.nanoseconds.convert(time, unit);

         // 将任务封装成实现delayed接口的消息体

         delayordertask<?> delayorder = new delayordertask<>(timeout, task);

         // 将消息体放到延时队列中

         delayqueue.put(delayorder);

     }

     /**

      * 删除任务

      *

      * @param task

      * @return

      */

     public boolean removetask(delayordertask task) {

         return delayqueue.remove(task);

     }

}

测试类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.delqueue;

import java.util.concurrent.timeunit;

import com.test.delayqueue.delayorderqueuemanager;

import com.test.delayqueue.delayorderworker;

public class test {

     public static void main(string[] args) {

         delayorderworker work1 = new delayorderworker(); // 任务1

         delayorderworker work2 = new delayorderworker(); // 任务2

         delayorderworker work3 = new delayorderworker(); // 任务3

         // 延迟队列管理类,将任务转化消息体并将消息体放入延迟对列中等待执行

         delayorderqueuemanager manager = delayorderqueuemanager.getinstance();

         manager.put(work1, 3000 , timeunit.milliseconds);

         manager.put(work2, 6000 , timeunit.milliseconds);

         manager.put(work3, 9000 , timeunit.milliseconds);

     }

}

ok 这就是项目中的具体使用情况,当然具体内容被忽略,整体框架就是这样,还有这里使用java的延时队列但是这种方式是有问题的如果如果down机则会出现任务丢失,所以也可以考虑使用mq、redis来实现……

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/QH_JAVA/article/details/78080969

查看更多关于Java延迟队列原理与用法实例详解的详细内容...

  阅读:44次