用队列实现的一个简单的生产者消费者模式,代码如下:
import java.util.LinkedList;
import java.util.Random;
//消费者线程
class A extends Thread{
private LinkedList<Integer> queue; //用一个队列表示商品缓冲区
public A(LinkedList<Integer> queue){
this.queue=queue;
}
public void run(){
while(true){
synchronized(queue) { //获得queue锁的线程才能继续执行
if(queue.size()==0){ //缓冲区没有商品
try {
queue.wait(); //线程等待,wait方法会释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("消费者线程消费:"+queue.poll()+" 目前剩余:");
for(int x:queue)
System.out.print(x+" ");
System.out.println();
queue.notifyAll(); //消费了一个商品,发出通知,表示缓冲区不满,生产者线程可以继续生产
try {
Thread.sleep(500); //避免输出过快
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//生产者线程
class B extends Thread{
private final LinkedList<Integer> queue;
public B(LinkedList<Integer> queue){
this.queue=queue;
}
public void run(){
while(true){
synchronized(queue) {
if(queue.size()>=5){ //这里设置的缓冲区最大容量是5
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int x=new Random().nextInt(100);
queue.offer(x);
System.out.print("生产者线程生产:"+x+" 目前剩余:");
for(int y:queue)
System.out.print(y+" ");
System.out.println();
queue.notifyAll(); //通知
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList<Integer> queue=new LinkedList<>();
new A(queue).start();
new B(queue).start();
}
}
运行结果: