//调用类
public class ProducterConsumerDemo2 {
public static void main(String[] args) {
new Thread(new Producter1()).start();
new Thread(new Producter1()).start();
new Thread(new Consumer1()).start();
new Thread(new Consumer1()).start();
}
}
//商品类
class Resource1{
private String name;
private int count = 1;
private boolean flag = false;
private Resource1(){}
private static Resource1 res = new Resource1();
public static Resource1 get(){
return res;
}
public synchronized void getName(){
while(!flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"-----消费者-----"+this.name);
flag = false;
this.notifyAll();
}
public synchronized void setName(String name){
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this.name = name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"---生产者---"+this.name);
flag = true;
this.notifyAll();
}
}
//生产者
class Producter1 implements Runnable{
Resource1 res1 = Resource1.get();
public void run() {
while(true)
res1.setName("商品");
}
}
//消费者
class Consumer1 implements Runnable{
Resource1 res2 = Resource1.get();
public void run() {
while(true)
res2.getName();
}
}