BlockingQueue介绍

package hw.lock;

import java.util.concurrent.ArrayBlockingQueue;

class Produce extends Thread{
	ArrayBlockingQueue<Integer> arrayBlockingQueue;
	int num=0;
	public Produce(ArrayBlockingQueue<Integer> arrayBlockingQueue) {
		// TODO Auto-generated constructor stub
		this.arrayBlockingQueue=arrayBlockingQueue;
	}
	
	@Override
	public void run() {
		while(true) {
		try {
			this.arrayBlockingQueue.put(num++);//放入产品
			System.out.println("生产产品,");
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	}
	
	
}

class Customer extends Thread{
	ArrayBlockingQueue<Integer> arrayBlockingQueue;
	public Customer(ArrayBlockingQueue<Integer> integers) {
		this.arrayBlockingQueue=integers;
	}
	
	@Override
	public void run() {
		while(true) {
		try {
			this.arrayBlockingQueue.take();//消费产品
			System.out.println("消费产品,");
			Thread.sleep(2000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	}
}
public class QueueBlocking {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayBlockingQueue<Integer> arrayBlockingQueue=new ArrayBlockingQueue<Integer>(10);
		for(int i=0;i<10;i++) {
			new Produce(arrayBlockingQueue).start();//多个线程执行
			//new Customer(arrayBlockingQueue).start();
		}
		
		for(int i=0;i<10;i++) {
			new Customer(arrayBlockingQueue).start();//多个线程执行
		}
	}

}

BolckingQueue是一个阻塞型的队列,线程安全,

初始化参数

第一个为他的存储大小,int capacity

第二个参数为boolean  falr 是否按照先进先出顺序出列

第三个参数为 Collection<? extends E> c,初始化时就加载到队列中

执行每个关于放数据和取数据的操作时候都会上锁,并且跟大小进行判断。

取数据和放数据:

 /**
     * Inserts the specified element at the tail of this queue if it is
     * possible to do so immediately without exceeding the queue's capacity,
     * returning <tt>true</tt> upon success and <tt>false</tt> if this queue
     * is full.  This method is generally preferable to method {@link #add},
     * which can fail to insert an element only by throwing an exception.
     *
     * @throws NullPointerException if the specified element is null
     */
    public boolean offer(E e) {//放数据入队列,如果满返回false
        if (e == null) throw new NullPointerException();
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == items.length)//count为队列大小
                return false;
            else {
                insert(e);
                return true;
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * Inserts the specified element at the tail of this queue, waiting
     * for space to become available if the queue is full.
     *
     * @throws InterruptedException {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public void put(E e) throws InterruptedException {//put会一直等待直到队列不为满
        if (e == null) throw new NullPointerException();
        final E[] items = this.items;
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            try {
                while (count == items.length)
                    notFull.await();
            } catch (InterruptedException ie) {
                notFull.signal(); // propagate to non-interrupted thread
                throw ie;
            }
            insert(e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * Inserts the specified element at the tail of this queue, waiting
     * up to the specified wait time for space to become available if
     * the queue is full.
     *
     * @throws InterruptedException {@inheritDoc}
     * @throws NullPointerException {@inheritDoc}
     */
    public boolean offer(E e, long timeout, TimeUnit unit)//放数据入队列,队列为满无法入队,如果这个操作能在timeout时间内完成则返回true,否则返回false

        throws InterruptedException {

        if (e == null) throw new NullPointerException();
	long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            for (;;) {
                if (count != items.length) {
                    insert(e);
                    return true;
                }
                if (nanos <= 0)
                    return false;
                try {
                    nanos = notFull.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    notFull.signal(); // propagate to non-interrupted thread
                    throw ie;
                }
            }
        } finally {
            lock.unlock();
        
    public E poll() {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (count == 0)
                return null;
            E x = extract();
            return x;
        } finally {
            lock.unlock();
        }
    }

    public E take() throws InterruptedException {
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            try {
                while (count == 0)
                    notEmpty.await();
            } catch (InterruptedException ie) {
                notEmpty.signal(); // propagate to non-interrupted thread
                throw ie;
            }
            E x = extract();
            return x;
        } finally {
            lock.unlock();
        }
    }

    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
	long nanos = unit.toNanos(timeout);
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            for (;;) {
                if (count != 0) {
                    E x = extract();
                    return x;
                }
                if (nanos <= 0)
                    return null;
                try {
                    nanos = notEmpty.awaitNanos(nanos);
                } catch (InterruptedException ie) {
                    notEmpty.signal(); // propagate to non-interrupted thread
                    throw ie;
                }

            }
        } finally {
            lock.unlock();
        }
    }

取数据和放数据基本方法一一对应,此处不再多说。

关于Size方法也是同步的,但是可能同步的只是size方法,在取size的时候因为BlockingQueue 里面的存数据的集合并没有上锁,所以在取count的时候由于可能有其他线程再次给队列添加数据,所以造成count可能有点奇特。


生产产品,4
生产产品,4
生产产品,6
生产产品,4
生产产品,6
生产产品,6
生产产品,7
生产产品,9
生产产品,10
生产产品,9

可能是这样的数据,不知道会不会有优化。。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值