自定義Lock和Condition實現生產消費模式

package com.example.test;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class TestAqs implements Lock {

    public class Aqs extends  AbstractQueuedSynchronizer{
        //加鎖
        @Override
        protected boolean tryAcquire(int arg) {
           if(compareAndSetState(0, arg)){
               setExclusiveOwnerThread(Thread.currentThread());
               return true;
           }
           return  false;
        }
        //釋放鎖
        @Override
        protected boolean tryRelease(int arg) {
            //判斷當前state是否爲0,爲0不持有當前對象鎖則拋出異常
            if(getState() == 0){
                throw new IllegalMonitorStateException();
            }
            setState(0);
            setExclusiveOwnerThread(null);
            return true;
        }

        //判斷當前鎖是否被持有
        @Override
        protected boolean isHeldExclusively() {
            return  this.getState() == 1;
        }

        public Condition newCondition(){
            return new ConditionObject();
        }
    }
    //創建實例對象,修改state的值來實現加鎖釋放鎖
    Aqs aqs = new Aqs();
    @Override
    public void lock() {
        aqs.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
      aqs.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return aqs.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return aqs.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        aqs.release(0);
    }

    @Override
    public Condition newCondition() {
        return aqs.newCondition();
    }

    public static final TestAqs testAqs = new TestAqs();
    public static final Condition empty = testAqs.newCondition();
    public static final Condition full = testAqs.newCondition();
    public static final Queue queue = new ConcurrentLinkedQueue();
    public static final  int max = 10;
    public static final Random random = new Random();
    public static void main(String[] args){
        //生產線程
        Thread producer = new Thread(() ->{
                while(true){
                    //獲取獨佔鎖
                    testAqs.lock();
                    try {
                        while(queue.size() == max){
                            System.out.println("隊列飽和");
                            full.await();
                        }
                        add(queue);
                        empty.signalAll();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        testAqs.unlock();
                    }
                }
        });

        //消費線程
        Thread consumer = new Thread(() -> {
                while (true) {
                    testAqs.lock();
                    System.out.println("消費者消費");
                    try {
                        while(queue.size() == 0){
                            empty.await();
                        }
                        reduce(queue);
                        full.signalAll();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        testAqs.unlock();
                    }
                }
        });

        producer.start();
        consumer.start();

    }

    public static void add( Queue queue){
            int value = random.nextInt(100);
            queue.add(value);
            System.out.println("隊列添加元素:" + value);
    }


    public static void reduce(Queue queue){
            Object value = queue.poll();
            System.out.println("隊列取出元素" + value);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章