首页 > 技术文章 > 简单的mq实现

tiankongjava 2017-03-03 16:14 原文

直接贴代码、、、

 1 package mq;
 2 
 3 /**
 4   * @author  作者 天空: 
 5   * @date 创建时间:2017年3月3日 下午2:07:46 
 6   * 
 7   */
 8 public class MqDemo {
 9 
10     /**
11      * @param args
12      * @throws InterruptedException 
13      */
14     public static void main(String[] args) throws InterruptedException {
15         Mq.getInstance().strat();//mq启动
16         for (int i = 0; i < 50; i++) {
17             Mq.getInstance().put(new Test(i));
18             System.out.println("....");//测试mq是否起作用
19         }
20         
21         Thread.sleep(10000);//模仿其他servlet 干活
22         Mq.getInstance().put(new Test(6666));
23         
24         Mq.getInstance().stop();//停止mq
25         Thread.sleep(10000);
26         Mq.getInstance().put(new Test(8888));
27     }
28     
29 }
30 
31 class Test implements Runnable{
32     
33     int i;
34     
35     Test(int i){
36         this.i=i;
37     }
38 
39     public void run() {
40         try {
41             Thread.sleep(100);//模仿任务干活
42             System.out.println(i);
43         } catch (InterruptedException e) {
44             e.printStackTrace();
45         }
46         
47     }
48     
49 }
 1 package mq;
 2 
 3 import java.util.Queue;
 4 import java.util.concurrent.ConcurrentLinkedQueue;
 5 import java.util.concurrent.ExecutorService;
 6 import java.util.concurrent.Executors;
 7 
 8 /**
 9   * @author  作者 天空: 
10  * @param <E>
11   * @date 创建时间:2017年3月3日 下午2:09:05 
12   * 
13   */
14 public class Mq {
15     
16     private Mq(){};
17 
18     private static Mq mq = new Mq();
19     private boolean flag=false;
20     private Queue<Runnable> queue=new ConcurrentLinkedQueue<Runnable>();
21     private ExecutorService pool = Executors.newFixedThreadPool(3);
22 
23     public Mq put(Runnable r){
24         queue.offer(r);
25         execute();//触发执行
26         return this;
27     }
28     
29     public void execute(){
30         while(queue.size()>0){
31             if(flag) pool.execute(queue.poll());
32         }
33     }
34     
35     public void strat(){
36         flag=true;
37         execute();
38     }
39     
40     public void stop(){
41         flag=false;
42     }
43     
44     public static Mq getInstance(){
45         return mq;
46     }
47     
48 }

 

推荐阅读