描述:设计一个超市货架程序,该货架可以摆放5件商品。若有空位则可以放商品,若有商品则可销售。(使用多线程)
代码:
package com.tust.shiyan8;
public class Second {
//商品数量
public int goodsCount = 5;
public static void main(String[] args){
Second second = new Second();
//生产者
new Thread(()->{
while (true){
synchronized (second){
if (second.goodsCount<5){
System.out.println("生产者生产了一件商品...");
second.goodsCount++;
System.out.println("p商品的剩余数量为:"+second.goodsCount);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
//消费者
new Thread(()->{
while (true){
synchronized (second){
if (second.goodsCount>0){
System.out.println("消费者消费了一件商品...");
second.goodsCount--;
System.out.println("c商品的剩余数量为:"+second.goodsCount);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
}
演示: