定义一个商品类,里面定义生产方法,消费方法,
定义一个生产者类,一个消费者类,传入 商品类对象
分别调用生产方法,消费方法
class Goods{
//商品名称
private String goodsName;
//商品库存
private int count;
//生产方法
public synchronized void set(String name) throws InterruptedException {
while(this.count>0) {
System.out.println("还有库存,等待消费者");
wait();
}
this.goodsName=name;
this.count++;
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
System.out.println("生产"+toString());
System.out.println("=========================================");
//生产完后通知消费者进程可以消费了
notifyAll();
}
//消费方法
public synchronized void get() throws InterruptedException {
while(this.count==0) {
System.out.println("没有库存了,等待生产者");
wait();
}
this.count--;
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
System.out.println("消费"+toString());
System.out.println("=========================================");
//消费完后通知生产者进程可以开始生产了
notifyAll();
}
@Override
public String toString() {
return "Goods [goodsName=" + goodsName + ", count=" + count + "]";
}
}
//生产者类
class producer implements Runnable{
private Goods goods;
public producer(Goods goods) {
super();
this.goods = goods;
}
public void run() {
while(true) {
try {
this.goods.set("奔驰c200l一辆");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//消费者类
class Consumer implements Runnable{
private Goods goods;
public Consumer(Goods goods) {
super();
this.goods = goods;
}
public void run() {
while(true) {
try {
this.goods.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
Goods goods=new Goods();
List<Thread> threadlist=new ArrayList<>();
for(int i=0;i<10;i++) {
Thread producerthread=new Thread(new producer(goods));
producerthread.setName("生产者线程"+i);
threadlist.add(producerthread);
}
for(int i=0;i<5;i++) {
Thread consumerthread=new Thread(new Consumer(goods));
consumerthread.setName("消费者线程"+i);
threadlist.add(consumerthread);
}
for (Thread thread : threadlist) {
thread.start();
}
}
}