zoukankan      html  css  js  c++  java
  • JAVA可阻塞队列-ArrayBlockingQueue

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

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

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

      抛异常 返回值 阻塞 超时
    Insert Add(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();
    
        }
    }
  • 相关阅读:
    Spring-data-jpa 笔记(一)
    grpc详解 java版
    快速入门正则表达式
    异常的处理
    一位资深程序员大牛给予Java初学者的学习路线建议
    this用法
    静态代码块与非静态代码块
    类的成员变量--构造器
    Java并发机制及锁的实现原理
    JAVA内存模型
  • 原文地址:https://www.cnblogs.com/duwenlei/p/5129298.html
Copyright © 2011-2022 走看看