为什么运行的结果中count不是从1开始的呢??
class Resource
{
private String name;
private int count=1;
private boolean flage=false;
public synchronized void set(String name)
{
//if(flage)
while(flage)
{
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);
flage=true;
//this.notify();
this.notifyAll();
}
public synchronized void out()
{
//if(!flage)
while(!flage)
{
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"--消费者--"+this.name);
flage=false;
//this.notify();
this.notifyAll();
}
}
//定义生产者类
class Producer implements Runnable
{
Resource r=new Resource();
public Producer(Resource r)
{
this.r=r;
}
int x=0;
public void run()
{
while(true)
{
if(x==0)
{
r.set("产品");
}
else
r.set("canp");
x=(x+1)%2;
}
}
}
//定义消费者类
class Consumer implements Runnable
{
Resource r=new Resource();
Consumer(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
public class ProductConsumerDemo {
public static void main(String[] args)
{
Resource r=new Resource();
new Thread(new Producer(r)).start();
new Thread(new Producer(r)).start();
new Thread(new Consumer(r)).start();
new Thread(new Consumer(r)).start();
}
}
运行结果:
Thread-0--生产者--产品-----22196
Thread-2--消费者--产品-----22196
Thread-1--生产者--canp-----22197
Thread-3--消费者--canp-----22197
Thread-1--生产者--产品-----22198
Thread-2--消费者--产品-----22198
Thread-0--生产者--canp-----22199
Thread-2--消费者--canp-----22199
Thread-1--生产者--canp-----22200
Thread-3--消费者--canp-----22200
Thread-1--生产者--产品-----22201
Thread-2--消费者--产品-----22201 |
|