AQS&管程模型详解

AQS&管程模型

MESA模型

img

管程模型

img

public void method() {
    synchronized (this) {
        // do something
    }
}

AQS模型

QQ截图20220702140458

Reentrantlock示例

简单示例

public class LockDemo {
    static Lock lock = new ReentrantLock();
    public static void method1() {
        lock.lock();
        try {
            System.out.println("execute method1");
        } finally {
            lock.unlock();
        }
    }
}

阻塞队列

public class LockConditionBlockQueue {
    private int size;
    public LockConditionBlockQueue(int size) {
        this.size = size;
    }
    private Queue<String> queue = new LinkedList<>();
    private Lock lock = new ReentrantLock();
    /**
     * 条件控制:控制队列满了的线程
     */
    private Condition fullCondition = lock.newCondition();
    /**
     * 条件控制:控制队列空了的线程
     */
    private Condition emptyCondition = lock.newCondition();
    private void product() {
        lock.lock();
        try {
            if (queue.size() == size) {
                try {
                    // 满了,就阻塞当前线程,等待唤醒
                    fullCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            String msg = UUID.randomUUID().toString();
            queue.offer(msg);
            System.out.println("生产消息:" + msg);
            // 生产消息后如果有队列空了而阻塞的线程,则通知线程可以消费了
            emptyCondition.signal();
        } finally {
            lock.unlock();
        }
    }
    private void consumer() {
        lock.lock();
        try {
            if (queue.size() == 0) {
                try {
                    // 队列为空,则阻塞,等待唤醒
                    emptyCondition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("消费消息:" + queue.poll());
            // 消费消息后如果有队列满了而阻塞的线程,则通知线程可以添加了
            fullCondition.signal();
        } finally {
            lock.unlock();
        }
    }
}
  • MESA
    • Synchronized(monitor)
    • Reentrantlock(AQS)
posted @ 2022-07-12 20:33  Faetbwac  阅读(79)  评论(0编辑  收藏  举报