之前写过Java实现阻塞队列 是以链表的形式实现的,最近闲着,又试了下数组形式的实现。直接上代码吧。
package com.xtli.queue;
import java.util.Random;
/*
* 阻塞队列。put方法,take方法。
* 数组实现。
* 定义队列的head和tail:
* head 指向第一个值;
* tail 指向最后一个为null的下标;
* 队列中的数量count
*
*/
public class MyBlockingQueue {
private Object[] a = null;
private int tail = 0;//tail指向最后一个为null的下标
private int head = 0;//head指向第一个有值的下标
private int count = 0;
private MyBlockingQueue() {
}
private MyBlockingQueue(int size) {
a = new Object[size];
}
public synchronized void put(Object obj) throws InterruptedException {
while(isFull()) {
System.out.println("【入队操作】阻塞,释放锁");
wait();
}
System.out.println("【入队操作】获取锁");
a[tail] = obj;
if(++tail == a.length) {
tail = 0;
}
count++;
System.out.println("【入队操作】队列值:" + toString());
notifyAll();
}
public synchronized Object take() throws InterruptedException {
while(isEmpty()) {
System.out.println("【出队操作】阻塞,释放锁");
wait();
}
System.out.println("【出队操作】获取锁");
System.out.println("【出队操作】队列值:" + toString());
Object re = a[head];
a[head] = null;
if(++head == a.length) {
head = 0;
}
count--;
notifyAll();
System.out.println("take值:" + re);
return re;
}
public boolean isEmpty() {
return count == 0;
}
public boolean isFull() {
return count == a.length;
}
public String toString() {
StringBuffer sb = new StringBuffer();
if(count > 0) {
for(int i=0;i<a.length;i++) {
sb.append(a[i]+",");
}
}
return sb.toString();
}
public static void main(String[] args) throws InterruptedException {
final MyBlockingQueue bq = new MyBlockingQueue(10);
Thread con = new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
Object re = bq.take();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
con.start();
Thread pro = new Thread(new Runnable() {
@Override
public void run() {
try {
while(true) {
Random r = new Random();
Integer a = new Integer(r.nextInt());
bq.put(a);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
pro.start();
}
}
运行之后,大概就是下面这个样子