package ProConDemo;
//创建资源
public class Goods {
private String name;
//计数器
private int count = 1;
//创建一个标记
private boolean flag;
//创建资源的生产行为
public synchronized void Sale(String name) {
//判断标记
while(flag)
//有资源就等待
try {wait();} catch (InterruptedException e) {e.printStackTrace();}
//没有资源就生产
this.name = name +"----"+count;
count++;
System.out.println(Thread.currentThread().getName()+"生产了"+this.name);
//生产完毕改标记
flag = true;
//唤醒所有等待线程
notifyAll();
}
//创建资源的消费行为
public synchronized void Buy() {
//判断标记
while(!flag)
//没有资源就等待
try {wait();} catch (InterruptedException e) {e.printStackTrace();}
//有资源就消费
System.out.println(Thread.currentThread().getName()+"消费了"+this.name);
//消费完毕改标记
flag = false;
//唤醒所有等待线程
notifyAll();
}
}
package ProConDemo;
//创建消费者任务类
public class Cou implements Runnable{
private Goods good;
//将资源对象作为参数传入消费者的构造函数中
public Cou(Goods good) {
this.good = good;
}
//覆盖run()
public void run() {
while(true)
good.Buy();
}
}
package ProConDemo;
//创建生产者任务类
public class Pro implements Runnable{
private Goods good;
//将资源对象作为参数传入生产者构造函数中
public Pro(Goods good) {
this.good = good;
}
//覆盖run()
public void run() {
while(true)
good.Sale("面包");
}
}
//执行
package ProConDemo;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建资源对象
Goods good = new Goods();
//创建生产与消费任务对象
Pro pro = new Pro(good);
Cou cou = new Cou(good);
//创建线程,并将任务对象传入
Thread t0 = new Thread(pro);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(cou);
Thread t3 = new Thread(cou);
//启动线程
t0.start();
t1.start();
t2.start();
t3.start();
}
}