Java线程同步工具-ArrayBlockingQueue

来源:互联网 发布:java工程师职业路线 编辑:程序博客网 时间:2024/06/05 13:33

ArrayBlockingQueue

JDK内部提供的同步队列,能够保证线程安全
这里写图片描述

从阻塞队列的结构可以看出阻塞队列是Collectuon集合的一个子类

主要同步方法:

  • put方法
 public void put(E e) throws InterruptedException {        checkNotNull(e);        final ReentrantLock lock = this.lock;        lock.lockInterruptibly();        try {            while (count == items.length)                notFull.await();            enqueue(e);        } finally {            lock.unlock();        }    }
  • take方法
 public E take() throws InterruptedException {        final ReentrantLock lock = this.lock;        lock.lockInterruptibly();        try {            while (count == 0)                notEmpty.await();            return dequeue();        } finally {            lock.unlock();        }    }

测试代码:

package com.zhiwei.thread;import java.util.concurrent.ArrayBlockingQueue;/** * 阻塞队列:可用于处理生产消费的问题 *  * 实现机制:put/take利用重入锁ReentrantLock实现同步效果 */public class ArrayBlockingQueueTest {    public static void main(String[] args) {        ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(3);        new Thread(new Runnable() {            @Override            public void run() {                while(true){                    try {                        Thread.sleep(1000);                        abq.put("Hello Java World");                        System.out.println(Thread.currentThread().getName()+":放入数据,剩余数据:"+abq.size());                    } catch (Exception e) {                        e.printStackTrace();                    }                   }            }        }).start();        new Thread(new Runnable() {            @Override            public void run() {                while(true){                    try {                        Thread.sleep(10000);                        abq.take();                        System.out.println(Thread.currentThread().getName()+":取出数据,剩余数据:"+abq.size());                    } catch (Exception e) {                        e.printStackTrace();                    }                   }            }        }).start();    }}
  • 效果
    这里写图片描述
原创粉丝点击