不知道哪里写错了结果只有:
生产水果:水果:0
消费水果:水果:0
[code="java"]
/**
- 生产1个水果,卖1个
-
@author 1
*
*/
public class NewProducerCustomer {public static void main(String[] args) {
Method m = new Method();
Producers p = new Producers(m);
Customers c = new Customers(m);new Thread(p).start(); new Thread(c).start();
}
}
class Fruit{
int id;
public Fruit(int id){
this.id = id;
}
public String toString(){
return "水果:"+id;
}
}
class Method{
int indext = 0;
Fruit f;
public synchronized void producer(Fruit f){
if(indext == 1){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.f = f;
this.notifyAll();
indext = 0;
}
public synchronized Fruit Consumption(){
if(indext == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
indext = 1;
return f;
}
}
class Producers implements Runnable{
Method m = null;
public Producers(Method m) {
this.m = m;
}
public void run() {
for(int i=0;i<10;i++){
Fruit f = new Fruit(i);
m.producer(f);
System.out.println("生产水果:"+f);
try {
Thread.sleep((int)Math.random()*200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Customers implements Runnable{
Method m = null;
public Customers(Method m) {
this.m = m;
}
public void run() {
Fruit f = m.Consumption();
System.out.println("消费水果:"+f);
try {
Thread.sleep((int)Math.random()*200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
[/code]