java链路调用_JAVA线程Disruptor核心链路应用(八)

16795abc0cdae8dafbeaf81239f91bd2.png

0400c45c1079338dd49554799abf6684.png

57743eddd47228b181186c4ee68c261a.png

e83201654f4540f6535c448ed92503c5.png

e44e16d7a41754daa612ddcfd7d3b8e6.png

ac7d50fa7ac24e1b1a8dabc5514fdd25.png

9a1c40c882e6f25ed571c5874e5c9197.png

import java.util.concurrent.atomic.AtomicInteger;

/**

* Disruptor中的 Event

* @author Alienware

*

*/

public class Trade {

private String id;

private String name;

private double price;

//在并发时实现线程安全

private AtomicInteger count = new AtomicInteger(0);

public Trade() {

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

public AtomicInteger getCount() {

return count;

}

public void setCount(AtomicInteger count) {

this.count = count;

}

}

import java.util.Random;

import java.util.concurrent.CountDownLatch;

import com.lmax.disruptor.EventTranslator;

import com.lmax.disruptor.dsl.Disruptor;

public class TradePushlisher implements Runnable {

private Disruptor disruptor;

private CountDownLatch latch;

private static int PUBLISH_COUNT = 1;

public TradePushlisher(CountDownLatch latch, Disruptor disruptor) {

this.disruptor = disruptor;

this.latch = latch;

}

public void run() {

TradeEventTranslator eventTranslator = new TradeEventTranslator();

for(int i =0; i < PUBLISH_COUNT; i ++){

//新的提交任务的方式

disruptor.publishEvent(eventTranslator);

}

latch.countDown();

}

}

class TradeEventTranslator implements EventTranslator {

private Random random = new Random();

public void translateTo(Trade event, long sequence) {

this.generateTrade(event);

}

private void generateTrade(Trade event) {

event.setPrice(random.nextDouble() * 9999);

}

}

import com.lmax.disruptor.EventHandler;

import com.lmax.disruptor.WorkHandler;

public class Handler1 implements EventHandler, WorkHandler{

//EventHandler

public void onEvent(Trade event, long sequence, boolean endOfBatch) throws Exception {

this.onEvent(event);

}

//WorkHandler

public void onEvent(Trade event) throws Exception {

System.err.println("handler 1 : SET NAME");

Thread.sleep(1000);

event.setName("H1");

}

}

import java.util.UUID;

import com.lmax.disruptor.EventHandler;

public class Handler2 implements EventHandler {

public void onEvent(Trade event, long sequence, boolean endOfBatch) throws Exception {

System.err.println("handler 2 : SET ID");

Thread.sleep(2000);

event.setId(UUID.randomUUID().toString());

}

}

import com.lmax.disruptor.EventHandler;

public class Handler3 implements EventHandler {

public void onEvent(Trade event, long sequence, boolean endOfBatch) throws Exception {

System.err.println("handler 3 : NAME: "

+ event.getName()

+ ", ID: "

+ event.getId()

+ ", PRICE: "

+ event.getPrice()

+ " INSTANCE : " + event.toString());

}

}

import com.lmax.disruptor.EventHandler;

public class Handler4 implements EventHandler {

public void onEvent(Trade event, long sequence, boolean endOfBatch) throws Exception {

System.err.println("handler 4 : SET PRICE");

Thread.sleep(1000);

event.setPrice(17.0);

}

}

import com.lmax.disruptor.EventHandler;

public class Handler5 implements EventHandler {

public void onEvent(Trade event, long sequence, boolean endOfBatch) throws Exception {

System.err.println("handler 5 : GET PRICE: " + event.getPrice());

Thread.sleep(1000);

event.setPrice(event.getPrice() + 3.0);

}

}

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import com.lmax.disruptor.BusySpinWaitStrategy;

import com.lmax.disruptor.EventFactory;

import com.lmax.disruptor.RingBuffer;

import com.lmax.disruptor.dsl.Disruptor;

import com.lmax.disruptor.dsl.EventHandlerGroup;

import com.lmax.disruptor.dsl.ProducerType;

public class Main {

@SuppressWarnings("unchecked")

public static void main(String[] args) throws Exception {

//构建一个线程池用于提交任务

ExecutorService es1 = Executors.newFixedThreadPool(1);

ExecutorService es2 = Executors.newFixedThreadPool(5);

//1 构建Disruptor

Disruptor disruptor = new Disruptor(

new EventFactory() {

public Trade newInstance() {

return new Trade();

}

},

1024*1024,

es2,

ProducerType.SINGLE,

new BusySpinWaitStrategy());

//2 把消费者设置到Disruptor中 handleEventsWith

//2.1 串行操作:

disruptor

.handleEventsWith(new Handler1())

.handleEventsWith(new Handler2())

.handleEventsWith(new Handler3());

//2.2 并行操作: 可以有两种方式去进行

//1 handleEventsWith方法 添加多个handler实现即可

//2 handleEventsWith方法 分别进行调用

disruptor.handleEventsWith(new Handler1(), new Handler2(), new Handler3());

disruptor.handleEventsWith(new Handler2());

disruptor.handleEventsWith(new Handler3());

//2.3 菱形操作 (一)

disruptor.handleEventsWith(new Handler1(), new Handler2())

.handleEventsWith(new Handler3());

//2.3 菱形操作 (二)

EventHandlerGroup ehGroup = disruptor.handleEventsWith(new Handler1(), new Handler2());

ehGroup.then(new Handler3());

//2.4 六边形操作

Handler1 h1 = new Handler1();

Handler2 h2 = new Handler2();

Handler3 h3 = new Handler3();

Handler4 h4 = new Handler4();

Handler5 h5 = new Handler5();

disruptor.handleEventsWith(h1, h4);

disruptor.after(h1).handleEventsWith(h2);

disruptor.after(h4).handleEventsWith(h5);

disruptor.after(h2, h5).handleEventsWith(h3);

//3 启动disruptor

RingBuffer ringBuffer = disruptor.start();

//设置唤醒的次数

CountDownLatch latch = new CountDownLatch(1);

long begin = System.currentTimeMillis();

es1.submit(new TradePushlisher(latch, disruptor));

latch.await();//进行向下

disruptor.shutdown();

es1.shutdown();

es2.shutdown();

System.err.println("总耗时: " + (System.currentTimeMillis() - begin));

}

}

多生产者模型:

6e4e532ee62c47b83b6d2fa437853d94.png

多消费者:

149ca490e39bae43eb3850feab5021fe.png

24e94883e3fe720920ba41883eec66cc.png

import java.util.concurrent.atomic.AtomicInteger;

public class Order {

private String id;

private String name;

private double price;

public Order() {

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

}

import com.lmax.disruptor.RingBuffer;

public class Producer {

private RingBuffer ringBuffer;

public Producer(RingBuffer ringBuffer) {

this.ringBuffer = ringBuffer;

}

public void sendData(String uuid) {

long sequence = ringBuffer.next();

try {

Order order = ringBuffer.get(sequence);

order.setId(uuid);

} finally {

ringBuffer.publish(sequence);

}

}

}

import java.util.Random;

import java.util.concurrent.atomic.AtomicInteger;

import com.lmax.disruptor.WorkHandler;

//消费者实现多消费的接口

public class Consumer implements WorkHandler {

private String comsumerId;

private static AtomicInteger count = new AtomicInteger(0);

private Random random = new Random();

public Consumer(String comsumerId) {

this.comsumerId = comsumerId;

}

public void onEvent(Order event) throws Exception {

Thread.sleep(1 * random.nextInt(5));

System.err.println("当前消费者: " + this.comsumerId + ", 消费信息ID: " + event.getId());

count.incrementAndGet();

}

public int getCount(){

return count.get();

}

}

import java.util.UUID;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.Executors;

import com.lmax.disruptor.EventFactory;

import com.lmax.disruptor.ExceptionHandler;

import com.lmax.disruptor.RingBuffer;

import com.lmax.disruptor.SequenceBarrier;

import com.lmax.disruptor.WorkerPool;

import com.lmax.disruptor.YieldingWaitStrategy;

import com.lmax.disruptor.dsl.ProducerType;

public class Main {

//1 创建RingBuffer

RingBuffer ringBuffer =

RingBuffer.create(ProducerType.MULTI,

new EventFactory() {

public Order newInstance() {

return new Order();

}

},

1024*1024,

new YieldingWaitStrategy());

//2 通过ringBuffer 创建一个屏障

SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();

//3 创建多个消费者数组:

Consumer[] consumers = new Consumer[10];

for(int i = 0; i < consumers.length; i++) {

consumers[i] = new Consumer("C" + i);

}

//4 构建多消费者工作池

WorkerPool workerPool = new WorkerPool(

ringBuffer,

sequenceBarrier,

new EventExceptionHandler(), //在失败的时候怎么处理

consumers);

//5 设置多个消费者的sequence序号 用于单独统计消费进度, 并且设置到ringbuffer中

ringBuffer.addGatingSequences(workerPool.getWorkerSequences());

//6 启动workerPool

workerPool

.start(Executors.newFixedThreadPool(5));

final CountDownLatch latch = new CountDownLatch(1);

for(int i = 0; i < 100; i++) {

final Producer producer = new Producer(ringBuffer);

new Thread(new Runnable() {

public void run() {

try {

latch.await();

} catch (Exception e) {

e.printStackTrace();

}

for(int j = 0; j<100; j++) {

producer.sendData(UUID.randomUUID().toString());

}

}

}).start();

}

Thread.sleep(2000);

System.err.println("----------线程创建完毕,开始生产数据----------");

latch.countDown();

Thread.sleep(10000);

System.err.println("任务总数:" + consumers[2].getCount());

}

static class EventExceptionHandler implements ExceptionHandler {

@Override

public void handleEventException(Throwable ex, long sequence, Order event) {

}

@Override

public void handleOnStartException(Throwable ex) {

}

@Override

public void handleOnShutdownException(Throwable ex) {

}

}

}

e3816a390cf21df08513d870c4e64c80.png

645319e767227bb120a3146cccf2028c.png

756219fdc0f3f2024adf626e0322dccf.png

b92bb2c526021a188c273f48796ffa23.png

2df51998d1678e0f8f1724261f7631b0.png

633fc86db5983aab367437ffacb73a26.png

b8752b9f08e7a11ec73c4cde970b8522.png

0d6d8134b8eb6b4010950ade1d05aa43.png

4c1008144aa2238b9db3ae2392838179.png

120cfba7813b4dc464f9d3f85309b277.png

4f67b1c0a934e078ab849740c7b94131.png

1723fbce94bf69c7ecf2733f3162ac76.png

63950e0b2892655007be96e621036700.png

ee3df41a28ff0c27bd1ae1a7efeefedd.png

1d43a4d3476e55591063642cc89d2e14.png

c4c29492c2b54faa83524bb78a47b32e.png

读读共享、读写互斥、写写互斥

c37227330944924ce87f6d6ea63b340f.png

b1b9d56c2a9663230497a9393cac7558.png

LockSupport :

Thread A = new Thread(new Runnable() {

@Override

public void run() {

int sum = 0;

for(int i =0; i < 10; i ++){

sum += i;

}

try {

Thread.sleep(4000);

} catch (InterruptedException e) {

e.printStackTrace();

}

LockSupport.park();//后执行

System.err.println("sum: " + sum);

}

});

A.start();

Thread.sleep(1000);

LockSupport.unpark(A);//先执行

Executors.newCachedThreadPool();

Executors.newFixedThreadPool(10);

ThreadPoolExecutor pool = new ThreadPoolExecutor(5,

Runtime.getRuntime().availableProcessors() * 2,

60,

TimeUnit.SECONDS,

new ArrayBlockingQueue<>(200),

new ThreadFactory() {

@Override

public Thread newThread(Runnable r) {

Thread t = new Thread(r);

t.setName("order-thread");

if(t.isDaemon()) {

t.setDaemon(false);

}

if(Thread.NORM_PRIORITY != t.getPriority()) {

t.setPriority(Thread.NORM_PRIORITY);

}

return t;

}

},

new RejectedExecutionHandler() {

@Override

public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

System.err.println("拒绝策略:" + r);

}

});

ReentrantLock reentrantLock = new ReentrantLock(true);

线程池:

ThreadPoolExecutor pool=new ThreadPoolExecutor(

5,

Runtime.getRuntime().availableProcessors()*2,

60,

TimeUnit.SECONDS,

new ArrayBlockingQueue<>(200),

new ThreadFactory() {

@Override

public Thread newThread(Runnable r) {

Thread thread=new Thread(r);

thread.setName("order-thread");

if(thread.isDaemon()){

thread.setDaemon(false);

}

if(Thread.NORM_PRIORITY!=thread.getPriority()){

thread.setPriority(Thread.NORM_PRIORITY);

}

return thread;

}

},

new RejectedExecutionHandler() {

@Override

public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

System.err.println("拒绝策略:"+r);

}

});

AQS架构:

16101613f5562654b406e01e2c1a039f.png

ad8cd0d6b9987ee3b69edf8228630c74.png

8d55161085b916348b625397f4db5d48.png

3748e999ebf5b4b3c1a0e90d60907bbc.png

f04d4c2debfc52c79bc8e91f9e3a77ee.png

ce69b262a88cd12e38608b082c9f8148.png

18a0c1ee9b5b3e39227f811cb739bcea.png

9f369c1ab38a18db9ef7abc645ba625d.png

7c1efcfb2463cd87658039ccff89114e.png

f9197e64b5c03c34198161aef93b5f3f.png

4f1f9de0545fd102f9a4e01994f63f68.png

922afb78cd347e78e84d67f79896940e.png

f82a157f39780e8dcc3cf8e519b8b5b5.png

8279622945e5379c7240cf945def9768.png

966c1e2196f8508e94e51df6957a964b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值