在基于数组的阻塞队列中加入5个班级:
package com.bfxy.thread.core.mycollection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class MyBlockingQueue {
public MyBlockingQueue() {
}
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(5);
AtomicInteger count = new AtomicInteger();
private final Object lock = new Object();
public void put(){
synchronized (lock) {
while (abq.size() == 5) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
abq.add("口语" + count.addAndGet(1) + "班");
System.out.println("新增口语"+count.get()+"班");
lock.notify();
}
}
public void take(){
synchronized (lock){
while(abq.size() == 0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("移除"+abq.poll());
lock.notify();
}
}
public ArrayBlockingQueue<String> getAbq() {
return abq;
}
public void setAbq(ArrayBlockingQueue<String> abq) {
this.abq = abq;
}
public AtomicInteger getCount() {
return count;
}
public void setCount(AtomicInteger count) {
this.count = count;
}
}
测试类:
package com.bfxy.thread.core.mycollection;
import java.util.concurrent.ArrayBlockingQueue;
public class MyBlockingQueueTest {
public static void main(String[] args){
ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(5);
MyBlockingQueue mbq = new MyBlockingQueue();
// mbq.take();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i<10;i++){
mbq.put();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i<5;i++){
mbq.take();
}
}
});
t1.start();
t2.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(mbq.getAbq().toString());
}
}
结果:
最终结果一致