主要通过wait()和notify()方法进行线程间的通讯
class Product extends Thread{ String name;
float price;
boolean flag = false; } class Productor extends Thread{ Product p; public Productor(Product p) { this.p = p; }
int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while(true){
synchronized(p){
//通知生产者生产
//p.notify();
if(!p.flag){
if(i%2 == 0){
p.name = "苹果";
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
p.price = 4.5f;
System.out.println("生产者生产了"+p.name+" 价格是"+p.price);
}
else{
p.name ="香蕉";
p.price = 2.5f;
System.out.println("生产者生产了"+p.name+" 价格是"+p.price);
}
i++;
p.flag = true;
p.notify(); }else{
//生产了产品后等待消费者消费
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} } class Consumer extends Thread{ Product p;
public Consumer(Product p) { this.p = p; }
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
while(true){
synchronized(p){
//通知启动消费者消费
//p.notify();
if(p.flag){
System.out.println("消费者消费了"+p.name+"价格是"+p.price);
p.flag = false;
p.notify();
}else{
//消费了产品后等待生产者生产
try {
p.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//main方法
public static void main(String[] args) { Product p = new Product(); Productor productor = new Productor(p);
Consumer consumer = new Consumer(p);
productor.start();
consumer.start(); }