阻塞队列使用
实现接口:
Iterator
collection
Queue
BlockingQueue
实现类:
ArrayBlocking:底层数组,有界
LinkedBlockingQueue:底层链表,无界(int最大值)
源码:
public void put(E e) throws InterruptedException {
Objects.requireNonNull(e);
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == items.length) //判断队列中的数据是否为0
notFull.await();
enqueue(e); //没有数据,加入
} finally {
lock.unlock();
}
}
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0) //判读队列中的数据是否为0
notEmpty.await();
return dequeue(); //有数据获取
} finally {
lock.unlock();
}
}
生产者消费者问题:
不用写锁
package day0920;
import java.util.concurrent.ArrayBlockingQueue;
public class Cooker extends Thread{
private ArrayBlockingQueue<String> cc;
private String name;
public Cooker(ArrayBlockingQueue<String> cc,String name){
this.cc = cc;
this.name = name;
}
@Override
public void run() {
while (true){
synchronized (Cooker.class){
try {
String nme = String.valueOf(System.currentTimeMillis());
cc.put(nme);
System.out.println(name + nme+ "做了一个包子");
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
package day0920;
import java.util.concurrent.ArrayBlockingQueue;
public class Eater extends Thread{
private ArrayBlockingQueue<String> ee;
private String name;
public Eater(ArrayBlockingQueue<String> ee,String name){
this.ee = ee;
this.name = name;
}
@Override
public void run() {
while (true){
synchronized (Eater.class){
try {
String take = ee.take();
System.out.println(name + take + "吃了一个包子");
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
package day0920;
import java.util.concurrent.ArrayBlockingQueue;
public class CookAndEat {
public static void main(String[] args) {
ArrayBlockingQueue<String> arr = new ArrayBlockingQueue<>(1);
Cooker cooker = new Cooker(arr,"灰太郎");
Cooker cooker2 = new Cooker(arr,"小福贵");
Cooker cooker3 = new Cooker(arr,"小当家");
Eater eater = new Eater(arr,"懒洋洋");
Eater eater2 = new Eater(arr,"小灰灰");
cooker3.start();
cooker2.start();
cooker.start();
eater.start();
eater2.start();
}
}