我正在学习Java,并且能够使用runnable对我现有的应用程序进行一些多线程处理。我现在正在看disruptor(在线程之间共享变量),但我无法弄清楚作者是如何实际产生线程的。
我看到他正在使用Executor,我用它在我的程序中提交runnable类,但在这个例子中没有提交(或runnable)。我只是从Oracle教程中学到了我所知道的,他们提到只有两种方法是扩展线程或实现runnable(我在这里看不到,但他确实将执行器提交给disruptor,这可能是他的线程化方式?)。我错过了什么,或者这个人是以不同的方式做事的?我的最终目标是理解这段代码(完美地运行),这样我就可以将它应用到我现有的(使用runnable)代码中。
以下是相关代码:
import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class App {
private final static int RING_SIZE = 1024 * 8;
private static long handleCount = 0;
private final static long ITERATIONS = 1000L * 1000L * 300L;
private final static int NUM_EVENT_PROCESSORS = 8;
private final static EventHandler<ValueEvent> handler =
new EventHandler<ValueEvent>() {
public void onEvent(final ValueEvent event,
final long sequence,
final boolean endOfBatch) throws Exception {
handleCount++;
}
};
public static void main(String[] args) {
System.out.println("Starting disruptor app.");
ExecutorService executor = Executors.newFixedThreadPool(NUM_EVENT_PROCESSORS);
Disruptor<ValueEvent> disruptor =
new Disruptor<ValueEvent>(ValueEvent.EVENT_FACTORY, executor,
new SingleThreadedClaimStrategy(RING_SIZE),
new SleepingWaitStrategy());
disruptor.handleEventsWith(handler);
RingBuffer<ValueEvent> ringBuffer = disruptor.start();
long start = System.currentTimeMillis();
long sequence;
ValueEvent event;
for (long x=0; x<ITERATIONS; x++) {
sequence = ringBuffer.next();
event = ringBuffer.get(sequence);
event.setValue(x);
ringBuffer.publish(sequence);
}
final long expectedSequence = ringBuffer.getCursor();
while (handleCount < expectedSequence) { }
long opsPerSecond = (ITERATIONS * 1000L) / (System.currentTimeMillis() - start);
System.out.printf("op/s: %d, handled: %d", opsPerSecond, handleCount);
}
}
更新:如果Disruptor正在处理线程的产生,那么我该如何将现有的runnable类提交给它呢?或者我是否需要再次修改代码?对不起,如果disruptor能够使用现有代码,或者我需要彻底改变我的东西,我会感到有点困惑。
答案 0 :(得分:7)
正如您所怀疑的,实际处理线程(通过提交工作项)是在Disruptor
内完成的。所以你需要查看its source code(运气好,它是开源的),找到这个:
public RingBuffer<T> start()
{
EventProcessor[] gatingProcessors = eventProcessorRepository.getLastEventProcessorsInChain();
ringBuffer.setGatingSequences(Util.getSequencesFor(gatingProcessors));
checkOnlyStartedOnce();
for (EventProcessorInfo<T> eventProcessorInfo : eventProcessorRepository)
{
executor.execute(eventProcessorInfo.getEventProcessor());
}
return ringBuffer;
}