高性能线程间消息通讯框架库 disruptor 入门

如下例子实现了生产者与消费者的经典例子java

import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;ci

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;get

public class LongEventMain
{
//消费者代码  it

public static void handleEvent(LongEvent event, long sequence, boolean endOfBatch)
    {
        System.out.println(event);
    }io

//生产者将数据初始化   event

public static void translate(LongEvent event, long sequence, ByteBuffer buffer)
    {
        event.set(buffer.getLong(0));
    }class

    public static void main(String[] args) throws Exception
    {
        // Executor that will be used to construct new threads for consumers
        Executor executor = Executors.newCachedThreadPool();thread

        // Specify the size of the ring buffer, must be power of 2.
        int bufferSize = 1024;import

        // Construct the Disruptor
        Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new, bufferSize, executor);sed

        // Connect the handler
        disruptor.handleEventsWith(LongEventMain::handleEvent);

        // Start the Disruptor, starts all threads running
        disruptor.start();

        // Get the ring buffer from the Disruptor to be used for publishing.
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        ByteBuffer bb = ByteBuffer.allocate(8);
        for (long l = 0; true; l++)
        {
            bb.putLong(0, l);

//生产者产生数据             ringBuffer.publishEvent(LongEventMain::translate, bb);             Thread.sleep(1000);         }     } }

相关文章
相关标签/搜索