JAVA可阻塞队列-ArrayBlockingQueue

  在前面的的文章,写了一个带有缓冲区的队列,是用JAVA的Lock下的Condition实现的,但是JAVA类中提供了这项功能,就是ArrayBlockingQueue,

  ArrayBlockingQueue是由数组支持的有界阻塞队列,次队列按照FIFO(先进先出)原则,当队列已经填满,在去增加则会导致阻塞,这种阻塞类似线程阻塞。

  ArrayBlockingQueue提供的增加和取出方法总结

 抛异常返回值阻塞超时
InsertAdd(e)offer(e)put(e)offer(e,time,unit)
remove  remove()  poll()take()  poll(time,unit)  
Examine  element()peek()空  

  使用ArrayBlockingQueue的一个子类BlockingQueue实现一个可阻塞队列,一个线程put另一个线程take,当队列为空时take等待,当线程满时put等待

  此实现方式没有线程互斥

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 可阻塞的队列
 * BlockingQueue
 * 此方式不能实现线程互斥
 * @author
 *
 */
public class BlockingQueueCommunicationTest {
    public static void main(String[] args) {
        final BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(3);
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                        System.out.println("线程"
                                + Thread.currentThread().getName() + "准备增加");
                        queue.put(1);
                        System.out.println("线程"
                                + Thread.currentThread().getName() + "已增加,队列有"
                                + queue.size() + "个");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                        System.out.println("线程"
                                + Thread.currentThread().getName() + "准备取走");
                        queue.take();
                        System.out.println("线程"
                                + Thread.currentThread().getName() + "已取走,队列剩余"
                                + queue.size() + "个");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
}

 

转载于:https://www.cnblogs.com/duwenlei/p/5129298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值