您的位置:首页 > 其它

非阻塞队列实现生产消费者模式

2016-07-09 09:25 267 查看
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());
}
}
}
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息