package BlockingQueues;
import java.util.PriorityQueue;
public class Test1 {
private int queueSize = 10;
private PriorityQueue queue = new PriorityQueue(queueSize);
public static void main(String[] args) {
Test test = new Test();
test.new Consumer().start();
test.new producer().start();
}
/**
* 消费者
* @author Administrator
*/
class Consumer extends Thread{
@Override
public void run() {
consume();
}
private void consume() {
while (true) {
synchronized (queue) {//queue锁
try {
while(queue.size()<=0){
queue.wait();//等待并释放锁
}
} catch (InterruptedException e) {
queue.notifyAll();
}
queue.poll();//获取并移除此队列的头,如果此队列为空,则返回 null
queue.notifyAll();//唤醒所有线程
System.out.println("consume size:"+queue.size());
}
}
}
}
/**
* 生产者
* @author Administrator
*/
class producer extends Thread{
@Override
public void run() {
produce();
}
private void produce() {
while(true){
synchronized (queue) {//queue锁
try {
while(queue.size()>0){
queue.wait();//等待并释放锁
}
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.add("abc");
queue.notifyAll();//唤醒所有线程
System.out.println("produce size:"+queue.size());
}
}
}
}
}