知识点总结(二)--Disruptor
- Disruptor
-
volatile关键字的作用:保证可见性,禁止指令重排,不保证原子性
-
简单用法:
-
//消费者 public class MsgConsumer implements EventHandler<MsgEvent>{ private String name; public MsgConsumer(String name){ this.name = name; } @Override public void onEvent(MsgEvent msgEvent, long l, boolean b) throws Exception { System.out.println(this.name+" -> 接收到信息: "+msgEvent.getValue()); } } //生产者处理 public class MsgProducer { private Disruptor disruptor; public MsgProducer(Disruptor disruptor){ this.disruptor = disruptor; } public void send(String data){ RingBuffer<MsgEvent> ringBuffer = this.disruptor.getRingBuffer(); long next = ringBuffer.next(); try{ MsgEvent event = ringBuffer.get(next); event.setValue(data); }finally { ringBuffer.publish(next); } } public void send(List<String> dataList){ dataList.stream().forEach(data -> this.send(data)); } } //触发测试 public class DisruptorDemo { @Test public void test(){ Disruptor<MsgEvent> disruptor = new Disruptor<>(MsgEvent::new, 1024, Executors.defaultThreadFactory()); //定义消费者 MsgConsumer msg1 = new MsgConsumer("1"); MsgConsumer msg2 = new MsgConsumer("2"); MsgConsumer msg3 = new MsgConsumer("3"); //绑定配置关系 disruptor.handleEventsWith(msg1, msg2, msg3); disruptor.start(); // 定义要发送的数据 MsgProducer msgProducer = new MsgProducer(disruptor); msgProducer.send(Arrays.asList("nihao","hah")); } }
-
集合的遍历删除,不能使用增强for循环:
-