当我运行这段代码
public class Test {
public static void main(String[] args) {
Disruptor<MyEvent> disruptor = new Disruptor<MyEvent>(new EventFactoryImpl<MyEvent>(),
Executors.newFixedThreadPool(2), new MultiThreadedClaimStrategy(32), new BusySpinWaitStrategy());
MyEventHandler myEventHandler1 = new MyEventHandler("1");
MyEventHandler myEventHandler2 = new MyEventHandler("2");
disruptor.handleEventsWith(myEventHandler1, myEventHandler2);
RingBuffer<MyEvent> ringBuffer = disruptor.start();
ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; l < 2; l++) {
bb.putLong(0, l);
long sequence = ringBuffer.next();
try {
MyEvent event = ringBuffer.get(sequence);
event.set(bb.getLong(0));
}
finally {
ringBuffer.publish(sequence);
}
}
}
}
public class MyEvent {
private long value;
public void set(long value) {
this.value = value;
}
public long get() {
return value;
}
}
public class MyEventHandler implements EventHandler<MyEvent> {
private String id;
public MyEventHandler(String id) {
this.id = id;
}
public void onEvent(MyEvent event, long sequence, boolean endOfBatch) {
System.out.println("id: " + id + ", event: " + event.get() + ", sequence: " + sequence + "," + Thread.currentThread().getName());
}
}
public class EventFactoryImpl<T> implements EventFactory<T> {
@SuppressWarnings("unchecked")
public T newInstance() {
return (T) new MyEvent();
}
}
我得到这个输出
id:1,事件:0,序列:0,pool-1-thread-1 id:1,事件:1,序列:1,pool-1-thread-1 id:2,事件:0,序列:0,pool-1-thread-2 id:2,事件:1,序列:1,pool-1-thread-2
但我希望每个事件只由一个单独的线程处理一次。我怎样才能让它发生?