生产者与消费者
先有一个容器,生产者只对容器中添加产品,消费者只对容器中消费产品。
当生产者检测到容器已满,就会进入wait状态,如果未满,则notifyAll来唤醒消费者线程。
当消费者线程检测到容器为空时,进入wait状态,如果不是,则消费,同时nitifyAll。
public class PandC {
public static void main(String[] args) {
Container container = new Container();
new Producer(container).start();
new Consumer(container).start();
}
}
//生产者
class Producer extends Thread{
Container container;
Producer(Container container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了第"+i+"个产品");
container.push(new Product(i));
}
}
}
//消费者
class Consumer extends Thread{
Container container;
Consumer(Container container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了第"+container.pop().id+"个产品");
}
}
}
//产品
class Product{
int id;
Product(int id){
this.id = id;
}
}
//容器
class Container{
//容器大小
Product[] products = new Product[10];
//计数
int count = 0;
public synchronized void push(Product product){
//如果容器已满,则生产者等待,消费者消费
if(count==products.length){
try {
this.wait(); //wait和sleep的不同之处在于,wait会释放锁
}catch (Exception e){
e.printStackTrace();
}
}
products[count] = product;
count++;
//通知消费者消费
this.notifyAll(); //唤醒其他所有线程
}
public synchronized Product pop(){
//如果没有产品了,等待生产者生产
if(count==0){
try {
this.wait();
}catch (Exception e){
e.printStackTrace();
}
}
count--;
Product product = products[count];
this.notifyAll();
return product;
}
}