阻塞队列
- 解耦合
- 削峰填谷
- 生产者消费者模型:
解耦合
削峰填谷
生产者消费者模型:
正常来说,wait通过notify唤醒,其他线程调用了take,在take的最后一步进行notify.
package thread;
class MyBlockingQueue{private String [] data=new String[1000];private volatile int head=0;private volatile int tail=0;private volatile int size=0;private final Object locker=new Object();public void put(String elem) throws InterruptedException {synchronized (this) {while (size == data.length) {//用while 让wait唤醒后还能再确认一次,是否条件成立this.wait();}data[tail] = elem;tail++;if (tail == data.length) {tail = 0;}size++;this.notify();}}public String take() throws InterruptedException {synchronized (this){while(size==0){this.wait();}String ret=data[head];head++;if(head==data.length){head=0;}size--;this.notify();return ret;}
}}
public class demo24 {public static void main(String[] args) {MyBlockingQueue queue= new MyBlockingQueue();
Thread t1=new Thread(()->{
while(true){try {String result=queue.take();System.out.println("消费元素"+result );} catch (InterruptedException e) {e.printStackTrace();}}});
Thread t2=new Thread(()->{int num=1;while(true){try {queue.put(num+"");System.out.println("生产元素"+num);num++;Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}
});
t1.start();
t2.start();}
}