public class MyBolckingQueue {
private LinkedList<Object> list = new LinkedList<Object>();
private AtomicInteger length = new AtomicInteger(0);
private int max;
private int min = 0;
public MyBolckingQueue(int max) {
this.max = max;
}
private final Object lock = new Object();
public void put(Object object) throws InterruptedException {
synchronized (lock) {
while (length.get() == max) {
lock.wait();
}
list.add(object);
length.incrementAndGet();
lock.notify();
}
}
public Object get() throws InterruptedException {
synchronized (lock) {
while (length.get() == min) {
lock.wait();
}
Object object = list.removeFirst();
length.decrementAndGet();
lock.notify();
return object;
}
}
public static void main(String[] args) throws InterruptedException {
MyBolckingQueue q = new MyBolckingQueue(5);
q.put("1");
q.put("2");
q.put("3");
q.put("4");
q.put("5");
new Thread() {
@Override
public void run() {
try {
q.put("6");
q.put("7");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
new Thread() {
@Override
public void run() {
try {
System.out.println(q.get());
System.out.println(q.get());
System.out.println(q.get());
System.out.println(q.get());
System.out.println(q.get());
System.out.println(q.get());
System.out.println(q.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
Thread.sleep(1000);
System.out.println(q.length);
}
}
Console:
1
2
3
4
5
6
7
0