一种典型的生产消费模型,借助队列解耦的模版

65 阅读1分钟

1. 背景

最近接触公司的项目,发现公司的代码对于解耦方面有一些比较好的写法,特地去掉敏感的部分做一些分享,希望能够总结一些有用的东西

2. 代码


/**
 * @Author: dingyawu
 * @Description: TODO
 * @Date: Created in 18:47 2023/3/16
 */
public interface InvokeHandler {
    /**
     * 返回改对象是否处于已启动状态
     */
    public boolean isStarted();

    /**
     * 启动此对象内部所有的线程
     */
    public void start();
    /**
     * 停止此对象内部所有的线程
     */
    public void stop();
}


public class MyThread implements Runnable, InvokeHandler {

    private boolean isStarted = false;

    private BlockingQueue<User> dataQueue;


    public MyThread(BlockingQueue<User> queue) {
        this.dataQueue = queue;
    }

    @Override
    public void start() {
        System.out.println("Start  MyThread success!");
        isStarted = true;
        Thread t = new Thread(this, "inner_MyThread");
        t.start();
    }

    public void put(User user) {
        try {
            dataQueue.put(user);
        } catch (InterruptedException e) {
            System.out.println("Queue is interrupted!" + e);
        }
    }


    @Override
    public void run() {
        System.out.println("execute at time:" + new Date());
        while(isStarted) {
            try {
                User user = dataQueue.take();
                System.out.println("consume:" + user.getUserName());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Exception happens!:" + e);
                isStarted = false;
                break;
            } catch (Throwable e) {
                System.out.println("THROW ERROR: " + e);
                throw e;
            }
        }
    }


    @Override
    public boolean isStarted() {
        return isStarted;
    }


    @Override
    public void stop() {
        isStarted = false;
    }
}



/**
 * @Author: dingyawu
 * @Description: 测试代码
 * @Date: Created in 18:22 2023/3/16
 */
public class TestMyThread {

    @Test
    public void test(){
        BlockingQueue<User> queue = new ArrayBlockingQueue<User>(1024);
        MyThread myThread = new MyThread(queue);
        myThread.start();

        for (int i = 0; i < 10000; i++) {
            myThread.put(new User("roy" + i));
        }

    }
}