数据结构和算法--阻塞队列:单锁

 private final String[] array = new String[10];
    private int tail = 0;

    ReentrantLock lock = new ReentrantLock();//锁对象
    Condition condition = lock.newCondition();//条件变量对象

    //1.@Synchronized
    //2. ReentrantLock
    public void offer(String s){
        //完全锁定
        lock.lock();
        //可打断锁
        //lock.lockInterruptibly();

        try {
            //单次判断容易造成多线程抢占资源,导致条件发生变化
            // 称之为虚假唤醒
//            if(isFull()){
//                condition.await();//进入阻塞状态
//            }
            //替换为while 循环判断
            while(isFull()){
                condition.await();//进入阻塞状态
            }
            array[tail] = s;
            tail++;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

完整实现

package com.zwz.ThreadQueue;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class BlockingQueueService<E> implements BlockingQueue<E> {

    private E[] array = (E[]) new Object[3];
    private int size = 0;
    private int tail = 0;
    private int head = 0;
    private ReentrantLock lock = new ReentrantLock();
    private Condition tailWail = lock.newCondition();
    private Condition headWail = lock.newCondition();


    @Override
    public void offer(E e) throws Exception {
        lock.lockInterruptibly();
        try {
            while (isFull()) {
                tailWail.await();
            }
            if(++tail > size){
                tail = 0;
            }
            array[tail] = e;
            size++;
            //唤醒poll的队列
            headWail.signal();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Boolean offer(E e, Long timeout) throws Exception {
        lock.lockInterruptibly();
        //使用纳秒处理
        try {
//            long t = TimeUnit.SECONDS.toNanos(timeout);
//            while (isFull()) {
//                if(t <= 0){
//                    return false;
//                }
//                t = tailWail.awaitNanos(t);
//            }
            //使用超时时间处理
            Boolean flag = true;
            while (isFull()) {
                System.out.println("flag-before:"+flag);
                if (!flag) {
                    return false;
                }
                flag = tailWail.await(timeout, TimeUnit.SECONDS);
                System.out.println("flag-after:"+flag);
            }
            System.out.println(e);

            if(++tail > size){
                tail = 0;
            }
            array[tail] = e;
            size++;

            //唤醒poll的队列
            headWail.signal();
        } finally {
            lock.unlock();
        }
        return true;
    }

    @Override
    public E poll() throws Exception {
        E e = null;
        lock.lockInterruptibly();
        try {
            while (isEmpty()) {
                headWail.await();
            }
            e = array[head];
            array[head] = null;
            head++;
            size--;
            //唤醒offer的队列
            //tailWail.signal();
        } finally {
            lock.unlock();
        }
        return e;
    }

    private Boolean isEmpty() {
        return size == 0;
    }

    private Boolean isFull() {
        return size == array.length;
    }

    @Override
    public List<E> getList() {
        List<E> list = new ArrayList<>();
        for (E e : array) {
            list.add(e);
        }
        return list;
    }


    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new BlockingQueueService<>();
        LocalDateTime now = LocalDateTime.now();
        new Thread(() -> {
            try {

                System.out.println(now);
                queue.offer(1);
                System.out.println(queue.getList());
                queue.offer(2);
                System.out.println(queue.getList());
                queue.offer(3);
                System.out.println(queue.getList());

                queue.offer(4, 5L);
                System.out.println(queue.getList());

                System.out.println("终止:"+Duration.between(now, LocalDateTime.now()).getSeconds());
            } catch (Exception e) {

            }
        }, "this").start();

        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println(queue.poll());
                System.out.println(queue.getList());
                System.out.println("读取:"+Duration.between(now, LocalDateTime.now()).getSeconds());

                //queue.offer(6);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }).start();

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值