Disruptor学习(1)

Disruptor它是一个开源的并发框架,并获得2011 Duke's 程序框架创新奖,能够在无锁的情况下实现网络的Queue并发操作。

来一个他的例子吧.绝对是hello worl级别的.

只有两个类,一个是执行类,一个是自己定义的类.
自己需要定义一个event类,

Java代码   收藏代码
  1. package com.trevorbernard.disruptor.examples;  
  2.   
  3. import com.lmax.disruptor.EventFactory;  
  4.   
  5. /** 
  6.  * WARNING: This is a mutable object which will be recycled by the RingBuffer. You must take a copy of data it holds 
  7.  * before the framework recycles it. 
  8.  */  
  9. public final class ValueEvent {  
  10.     private String value;  
  11.   
  12.     public String getValue() {  
  13.         return value;  
  14.     }  
  15.   
  16.     public void setValue(String value) {  
  17.         this.value = value;  
  18.     }  
  19.   
  20.     public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>() {  
  21.         public ValueEvent newInstance() {  
  22.             return new ValueEvent();  
  23.         }  
  24.     };  
  25. }  


这里要用到一个factory类,作用就是生成定义的那个类.

执行类

Java代码   收藏代码
  1. package com.trevorbernard.disruptor.examples;  
  2.   
  3. import java.util.UUID;  
  4. import java.util.concurrent.ExecutorService;  
  5. import java.util.concurrent.Executors;  
  6.   
  7. import com.lmax.disruptor.EventHandler;  
  8. import com.lmax.disruptor.RingBuffer;  
  9. import com.lmax.disruptor.dsl.Disruptor;  
  10.   
  11. public class Simple {  
  12.     @SuppressWarnings("unchecked")  
  13.     public static void main(String[] args) {  
  14.         ExecutorService exec = Executors.newCachedThreadPool();  
  15.         // Preallocate RingBuffer with 1024 ValueEvents  
  16.         Disruptor<ValueEvent> disruptor = new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, 1024, exec);  
  17.         final EventHandler<ValueEvent> handler = new EventHandler<ValueEvent>() {  
  18.             // event will eventually be recycled by the Disruptor after it wraps  
  19.             public void onEvent(final ValueEvent event, final long sequence, final boolean endOfBatch) throws Exception {  
  20.                 System.out.println("Sequence: " + sequence+"   ValueEvent: " + event.getValue());  
  21.             }  
  22.         };  
  23.   
  24.         disruptor.handleEventsWith(handler);  
  25.         RingBuffer<ValueEvent> ringBuffer = disruptor.start();  
  26.         for (long i = 10; i < 15; i++) {  
  27.             String uuid =String.valueOf(i)    ;  
  28.             long seq = ringBuffer.next();  
  29.             ValueEvent valueEvent = ringBuffer.get(seq);  
  30.             valueEvent.setValue(uuid);  
  31.             ringBuffer.publish(seq);  
  32.         }  
  33.         disruptor.shutdown();  
  34.         exec.shutdown();  
  35.     }  
  36. }  



设置一个事件的监听,这里只是打印一下.
然后就是把我们定义的事件写入到RingBuffer,然后发布.负责监听的就会接受到.

http://huangyunbin.iteye.com/blog/1919246

猜你喜欢

转载自m635674608.iteye.com/blog/2295740