废话不多说直接上代码。嘻嘻!
代码实现:
public class BlockQueueTest {
final LinkedList<Object> items;
private int capticy;
public BlockQueueTest(int i) {
this.capticy =i;
this.items = new LinkedList<Object>();
}
public int getCapticy() {
return capticy;
}
//添加元素
public synchronized void add(Object o) throws InterruptedException {
//需要判断队列是否满了。满了就阻塞
while (isFull()){
wait();//阻塞生产者
}
items.offer(o);
notifyAll(); //唤醒消费者去删除队列的元素.
}
//移出元素(出队)
public synchronized Object remove() throws InterruptedException {
//需要判断队列是位空
//这块推荐使用while 而不用if, 因为多线程下可能会出现虚假唤醒, 当某个消费者线程被唤醒时,它可能并没有发现队列为空,从而导致虚假唤醒问题。
while (isEmpty()){
wait();//阻塞消费者
}
Object first = items.poll();
notifyAll(); //唤醒生产者去添加元素
return first;
}
public boolean isFull(){
return items.size()>=this.capticy;
}
public boolean isEmpty(){
return items.size()==0;
}
public static void main(String[] args) throws InterruptedException {
BlockQueueTest blockQueueTest = new BlockQueueTest(2);
for (int i = 0; i < 2;i++) {
new Thread(()->{
try {
Object remove = blockQueueTest.remove();
System.out.println(remove);
} catch (InterruptedException e) {
}
}).start();
}
Thread.sleep(10000);
blockQueueTest.add("2");
System.out.println(blockQueueTest.items.size());
blockQueueTest.add("2");
blockQueueTest.add("2");
blockQueueTest.add("2");
blockQueueTest.add("2");
blockQueueTest.add("2");
}
}
上述代码实现:
需要判断队列是否为空,或者是否占满,然后去阻塞对应的方法。
引入synchronized 关键字,保证同一方法,同一时刻只能被一个线程所调用。
以上就是一个简单的阻塞队列的代码实现,希望能够帮助到你。