阻塞队列的特点:a.解耦合,b.削峰填谷.
注意:wait()方法要和while配合使用.
public class MyBlockingQueue {
private volatile String[] elems = new String[10];
private volatile int front = 0;
private volatile int tail = 0;
private volatile int size = 0;
public void put(String elem) throws InterruptedException {
synchronized (this) {
while (elems.length == size) {
this.wait();
}
elems[tail++] = elem;
++size;
if (tail == elems.length) {
tail = 0;
}
this.notify();
}
}
public String take() throws InterruptedException {
synchronized (this) {
while (size == 0) {
this.wait();
}
String elem = elems[front++];
--size;
if (front == elems.length) {
front = 0;
}
this.notify();
Thread.sleep(1000);
return elem;
}
}
}
public class Test {
public static MyBlockingQueue myBlockingQueue = new MyBlockingQueue();
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
int count = 0;
while (true) {
try {
myBlockingQueue.put(count + "");
System.out.println("生产:" + count);
++count;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(() -> {
int count = 0;
while (true) {
try {
String elem = myBlockingQueue.take();
System.out.println("消费:" + count);
++count;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}