高性能線程間消息通訊框架庫 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);         }     } }

相關文章
相關標籤/搜索