package thread;
import java.util.LinkedList;
import java.util.Queue;
public class Demo16{
private static Queue<Integer> q=new LinkedList<Integer>();
public static void main(String[] args) {
int maxSize=2;
new Producer(q,maxSize,"生产者1").start();
new Producer(q,maxSize,"生产者2").start();
new Consumer(q,maxSize,"消费者1").start();
new Consumer(q,maxSize,"消费者2").start();
new Consumer(q,maxSize,"消费者3").start();
}
static class Producer extends Thread{
Queue<Integer> q;
int maxSize;
String name;
public Producer(Queue<Integer> q,int maxSize,String name) {
this.q=q;
this.maxSize=maxSize;
this.name=name;
}
public void run() {
while(true) {
System.out.println(name+ "等待获得队列的锁");
synchronized(q) {
System.out.println(name+ "获得队列的锁");
if(q.size()>=maxSize) {
System.out.println("生产已经满员,"+name+"线程请等待。。。");
try {
//如果生产已经满员了,则生产者进入等待的状态,等待消费者的唤醒(消费者消费之后,maxSize不是最大值了就唤醒所有的线程)
q.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num=(int)(int)(Math.random()*100);
q.add(num);
//唤醒所有的线程,等待CPU调度其一获取锁
q.notifyAll();
System.out.println(name+"生产一个商品==>"+num+"剩余的q-->"+q);
try {
Thread.sleep(1000L);
System.out.println(name+ "释放队列的锁");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Consumer extends Thread{
Queue<Integer> q;
int maxSize;
String name;
public Consumer(Queue<Integer> q,int maxSize,String name) {
this.q=q;
this.maxSize=maxSize;
this.name=name;
}
public void run() {
while(true) {
System.out.println(name+ "等待获得队列的锁");
synchronized(q) {
System.out.println(name+ "获得队列的锁");
if(q.size()==0) {
System.out.println(name+"暂时没有商品,线程请等待。。。");
try {
//如果没有商品,则线程释放锁,进入等待状态,等待生产者的的唤醒
q.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int num=q.poll();
//唤醒所有的线程,等待CPU调度其一获取锁
q.notifyAll();
System.out.println(name+"消费一个商品==>"+num+"剩余的q-->"+q);
try {
Thread.sleep(500L);
System.out.println(name+ "释放队列的锁");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}