1.生产者消费者问题
生产者消费者类
public class Producer {
public void produce(){
System.out.println("生产一个");
}
}
public class Consumer {
public void consumer(){
System.out.println("消费一个");
}
}
超市实体类
public class SuperMark {
// 此超市最大库存是3
// 当超市库存为0时,消费者不能消费
// 当超市库存==3时,生产者不能生产
// 最大库存
private final int MAX_STORE = 3;
// 当前库存
private int currentStore = 3;
Producer producer;
Consumer consumer;
public SuperMark() {
producer = new Producer();
consumer = new Consumer();
}
public synchronized void stockProduct() {
while (MAX_STORE == currentStore) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
producer.produce();
currentStore++;
System.out.println("当前库存" + currentStore);
notify();
}
public synchronized void sellProduct(){
while (0 == currentStore) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
consumer.consumer();
currentStore--;
System.out.println("当前库存"+currentStore);
notify();
}
消费和生产线程类
class ProduceThread extends Thread{
SuperMark superMark;
public ProduceThread(SuperMark superMark){
this.superMark=superMark;
}
@Override
public void run() {
for(int i=0;i<10;i++){
superMark.stockProduct();
}
}
}
class ConsumerThread extends Thread{
SuperMark superMark;
public ConsumerThread(SuperMark superMark){
this.superMark=superMark;
}
@Override
public void run() {
for(int i=0;i<10;i++){
superMark.sellProduct();
}
}
}
测试类
public static void main(String[] args) {
SuperMark superMark = new SuperMark();
ProduceThread thread1 = new ProduceThread(superMark);
ConsumerThread thread2 = new ConsumerThread(superMark);
ProduceThread thread3 = new ProduceThread(superMark);
ConsumerThread thread4 = new ConsumerThread(superMark);
thread1.start();
thread3.start();
thread4.start();
thread2.start();
}
结果
消费一个
当前库存2
消费一个
当前库存1
消费一个
当前库存0
生产一个
当前库存1
生产一个
当前库存2
可以看出库存不会大于3和低于0