package day2;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class BlockingQueue {
private ReentrantLock lock = new ReentrantLock();
private Condition notFull = lock.newCondition();
private Condition notEmpty = lock.newCondition();
private LinkedList<String> data = new LinkedList<>();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public void push(String value) {
lock.lock();
try {
while(data.size()==capacity) {
try {
System.out.println("队列已满,请等待");
notFull.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
data.addLast(value);
notEmpty.signal();
}finally {
lock.unlock();
}
}
public String get() {
lock.lock();
String value=null;
try {
while(data.isEmpty()) {
try {
System.out.println("队列为空,请等待");
notEmpty.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
value = data.removeFirst();
notFull.signal();
}finally {
lock.unlock();
}
return value;
}
public static void main(String[] args) {
BlockingQueue queue = new BlockingQueue(1);
for(int i = 0;i<5;i++) {
new Thread() {
public void run() {
System.out.println("取到值"+queue.get());
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
for(int i = 0;i<5;i++) {
new Thread() {
public void run() {
queue.push("shidebin");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
}
}
console输出:
队列为空,请等待
队列为空,请等待
取到值shidebin
队列为空,请等待
队列为空,请等待
取到值shidebin
队列已满,请等待
取到值shidebin
队列为空,请等待
队列已满,请等待
取到值shidebin
取到值shidebin