对远程数据库的操作,采用disruptor能够很好解决死锁,
首先是定义一个抽象类,实现Runnable接口
public abstract class Task implements Runnable { public Task(){} } public class TaskEvent { private Task tk; public Task getTask() { return tk; } public void setTask(Task tk) { this.tk = tk; } public final static EventFactory<TaskEvent> EVENT_FACTORY = new EventFactory<TaskEvent>() { public TaskEvent newInstance() { return new TaskEvent(); } }; public class TaskEventHandler implements EventHandler<TaskEvent> { // 执行接口函数onEvent执行 public void onEvent(TaskEvent event, long sequence, boolean endOfBatch) throws Exception { event.getTask().run(); } } } import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import com.zhenhai.bonecp.CustomThreadFactory; import com.zhenhai.disruptor.BatchEventProcessor; import com.zhenhai.disruptor.RingBuffer; import com.zhenhai.disruptor.SequenceBarrier; import com.zhenhai.disruptor.YieldingWaitStrategy; import com.zhenhai.disruptor.dsl.ProducerType; /** * 使用方法 DisruptorHelper.initAndStart(); Task tt=new Taska(); DisruptorHelper.produce(tt); DisruptorHelper.shutdown(); * * */ public class DisruptorHelper { /** * ringbuffer容量,最好是2的N次方 */ private static final int BUFFER_SIZE = 1024 * 1; private static int group=2; private RingBuffer<TaskEvent> ringBuffer[]; private SequenceBarrier sequenceBarrier[]; private TaskEventHandler handler[]; private BatchEventProcessor<TaskEvent> batchEventProcessor[]; private static DisruptorHelper instance; private static boolean inited = false; private static ScheduledExecutorService taskTimer=null; //JDK 创建一个使用单个 worker 线程的 Executor,以无界队列方式来运行该线程。 private ExecutorService execute[]; //启动监视线程 static { System.out.println("init DisruptorHelper!!!!!!!!!!!!!!!!!"); instance = new DisruptorHelper(); instance.init(); inited = true; System.out.println("init DisruptorHelper end!!!!!!!!!!!!!!!!!"); } |