测试类
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Goods goods = new Goods();
Producer producer = new Producer(goods);//Producer类中的构造方法必须传参
//创建多线程
Thread t1 = new Thread(producer,"生产者线程1");
Thread t2 = new Thread(producer,"生产者线程2");
Consumer consumer = new Consumer(goods);
Thread t3 = new Thread(consumer,"消费者线程1");
Thread t4 = new Thread(consumer,"消费者线程2");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
1.商品类
public class Goods {
private String name = "包子";//商品类拥有的属性
int index = 0;//用来记录生产了多少个包子
boolean flag = true;//设置一个标记用来判断是否需要生产或者消费商品
//生产
public synchronized void producer() {
//判断是否要等待
while(flag==false) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
index++;
if(index>5) {
return;
}
flag = !flag;
System.out.println(Thread.currentThread().getName()+"生产了第"+index+"个包子");
notifyAll();
}
//
public synchronized void consumer() {
//判断是否为真,为真的时候正在生产,生产的时候需要等待
while(flag == true) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"消费了第"+index+"个包子");
System.out.println("--------------");
flag = !flag;
notifyAll();
}
}
2.生产者线程类
public class Producer implements Runnable{
//构造方法里面传入商品对象
Goods goods = new Goods();
public Producer(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(goods.index<5) {
goods.producer();
}
}
}
3.消费者类
public class Consumer implements Runnable{
Goods goods = new Goods();
public Consumer(Goods goods) {
this.goods = goods;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(goods.index<5) {
goods.consumer();
}
}
}
结果: