①先写一个普通的队列(通过”循环队列的方式来实现“)
②加上线程安全(使用synchronized进行加锁控制)
③加上阻塞功能(put插入元素的时候,判定如果队列满了,在循环中进行wait;take取出元素的时候,判定如果队列为空,在循环中进行wait)
//①先写循环队列
private int[] elems = new int[1000];
private volatile int size = 0;
private int head = 0;
private int tail = 0;
//②加上线程安全(使用synchronized进行加锁控制)
//③加上阻塞功能(put插入元素的时候,判定如果队列满了,在循环中进行wait;take取出元素的时候,判定如果队列为空,在循环中进行wait)
public void put(int value) throws InterruptedException {
synchronized (this) {
while (size == elems.length) {
wait();
}
elems[tail] = value;//每次把新数值放在tail所在位置
tail = (tail + 1) % elems.length;//求余数。循环队列的特色
size++;
notifyAll();
}
}
public int take() throws InterruptedException {
int ret = 0;
synchronized (this) {
while (size == 0) {
wait();
}
ret = elems[head];//队列遵循”先进先出“,所以从对头取元素
head++;
if (head == elems.length) {
head = 0;
}
size--;
notifyAll();
}
return ret;
}
public synchronized int size() {
return size;
}
//测试代码
public static void main(String[] args) throws InterruptedException {
BlockingQueue blockingQueue = new BlockingQueue();
Thread customer = new Thread(() -> {
while (true) {
try {
int value = blockingQueue.take();
System.out.println("消费元素" + value);//消费者——从阻塞队列中取元素
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}, "消费者");
customer.start();
Thread producter = new Thread(() -> {
Random random = new Random();
while (true) {
try {
int num = random.nextInt(100);
System.out.println("生产元素" + num);//生产者——从阻塞队列中添加元素
blockingQueue.put(num);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}, "生产者");
producter.start();
customer.join();
producter.join();
}
}