目录
- 手撕一个阻塞队列
- 代码
- 讲解
手撕一个阻塞队列
要手撕一个阻塞队列:就要实现一个普通的队列,加上阻塞,加上锁
代码
java">class MyBlockingQueue{private String[] elems=null;private int tail=0;private int head=0;private int size=0;private Object locker=new Object();public MyBlockingQueue(int capacity){elems=new String[capacity];}public void put(String elem) throws InterruptedException {synchronized (locker){while(size>=elems.length){locker.wait();}elems[tail]=elem;tail++;if(tail>=elems.length){tail=0;}size++;locker.notify();}}public String take() throws InterruptedException {String elem=null;synchronized (locker){while(size==0){locker.wait();}elem=elems[head];size--;if(head>= elems.length){head=0;}size--;locker.notify();}return elem;}
}
public class ThreadDemo29 {public static void main(String[] args) {MyBlockingQueue myBlockingQueue=new MyBlockingQueue(100);Thread t1=new Thread(()->{int n=1;while(true) {try {myBlockingQueue.put(n + " ");System.out.println("生产元素:" + n);n++;} catch (InterruptedException e) {throw new RuntimeException(e);}}});Thread t2=new Thread(()->{while (true){try {String take = myBlockingQueue.take();System.out.println("消费元素:"+take);Thread.sleep(500);} catch (InterruptedException e) {throw new RuntimeException(e);}}});t1.start();t2.start();}
}
讲解
基于这个阻塞队列,就可以写一个简单的生产者消费者模型(最核心的部分是阻塞队列,使用synchronized和wait/notify达到 线程安全 &阻塞)了
实际上,生产者消费者模型,往往是多个生产者多个消费者。
这里的生产者和消费者往往不仅仅是一个线程,也可能是一个独立的服务器程序,甚至是一组服务器程序