自己写了个MQ

闲来无事,按照自己的理解写了一个简易版粗糙MQ

队列

package com.xd.test;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Zhangxd
 * @Date: 2021/12/31/10:32
 * @Description:
 */
public class Queue {
    static final String topic="A,B,C";
    static final PriorityBlockingQueue<String> messageQueue = new PriorityBlockingQueue<>();
    static final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        for (String s : topic.split(",")) {
            new Thread(() -> {
                try {
                    getConsumer(s);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
            arrayList.add(s);
        }
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("输入你要发送的Topic:"+topic);
            String propation = sc.next();
            if (!arrayList.contains(propation)){
                System.out.println("输入的分区无效!");
                continue;
            }
            System.out.println("输入一条消息:");
            pushMsg(propation+"-"+sc.next());
        }
    }

    public static void getConsumer(String s) throws InterruptedException {
        try {
            while (true) {
                    Thread.sleep(1000);
                try {
                    lock.lock();
                    if (!messageQueue.isEmpty()) {
                        assert messageQueue.peek() != null;
                        int i = messageQueue.peek().lastIndexOf("-");
                        String substring = messageQueue.peek().substring(0,i);
                        if (substring.equals(s)){
                            String poll = messageQueue.poll();
                            assert poll != null;
                            System.out.println("消费者"+s+"消费消息:" + poll.substring(i+1));
                            System.out.println("队列现状:" + messageQueue);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void pushMsg(String msg) {
        messageQueue.offer(msg);
    }
}

生产者与消费者

package com.xd.test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Zhangxd
 * @Date: 2022/01/12/10:53
 * @Description:
 */
public class LocalTest {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            list.add(i);
        }
        List<Integer> newList = new ArrayList<>();
        //创建线程池
        ExecutorService exec = Executors.newFixedThreadPool(10);
        final CountDownLatch countDownLatch = new CountDownLatch(list.size());
        list.forEach(s -> exec.execute(() -> {
            try {
              Thread.sleep(10);
              newList.add(s);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            System.out.println(Thread.currentThread().getName() + "正在处理" + s);
        }));
        try {
            countDownLatch.await();
        } catch (Exception e) {

        } finally {
            exec.shutdown();
        }
        System.out.println(newList.size());
        System.out.println(newList);
    }
}

package com.xd.test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Zhangxd
 * @Date: 2021/12/31/9:42
 * @Description:
 */
public class Test1 {
    static Integer count = 0;
    static Lock lock = new ReentrantLock();
    public static void main(String[] args) {
        new Thread(() -> {
            Thread.currentThread().setName("A线程");
            for (int i = 0; i < 10; i++) {
                try {
                    getCount();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(() -> {
            Thread.currentThread().setName("B线程");
            for (int i = 0; i < 10; i++) {
                try {
                    getCount();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    public static void getCount() throws InterruptedException {
//        lock.lock();
        if (lock.tryLock(5, TimeUnit.SECONDS)){
            try {
                count++;
                System.out.println(Thread.currentThread().getName()+count);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值