手撕BlockingQueue
public class RequestQueue {
private final Queue<Request> queue = new LinkedList<>();
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public Request getRequest() {
try {
lock.lock();
while (queue.peek() == null) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return queue.remove();
} finally {
lock.unlock();
}
}
public void putRequest(Request request) {
try {
lock.lock();
queue.offer(request);
condition.signalAll();
} finally {
lock.unlock();
}
}
}
生产者-消费者模式
在实现生产者消费者问题时,可以采用三种方式:
1.使用Object的wait/notify的消息通知机制
2.使用Lock的Condition的await/signal的消息通知机制
3.使用BlockingQueue实现
一.wait/notify实现生产者和消费者模式
public class ProductAndConsumer{
/*
1.生产者不断的向里面加东西
2.消费者不断地取东西
3.生产者发现容器里满了就wait
4.消费者发现容器里没东西了就wait
5.生产者生产东西唤醒消费者
6.消费者消费东西唤醒生产者
7.锁对象要是同一个对象才行*/
public static void main(String[] args){
ProductAndConsumer ps = new ProductAndConsumer();
Resources resources = ps.new Resources(10,new LinkedList<Product>());
new Thread(ps.new Producer(resources)).start();
new Thread(ps.new Consumer(resources)).start();
}
class Product{
String name;
public Product(String name) {
this.name = name;
}
public String getName()