class Resouce{
private String name;
private int count;
boolean flag=false;
public synchronized void produce(String name){
while(flag)
try{this.wait();}catch(Exception e){}
this.name=name;
System.out.println(Thread.currentThread().getName()+"生产者"+" ->"+this.name+count++);
flag=true;
this.notifyAll();
}
public synchronized void consumer(){
while(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"消费者 --->"+this.name+count);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable{
Resouce r;
public Producer(Resouce r){
this.r=r;
}
public void run(){
while(true){
r.produce("商品");
}
}
}
class Consumer1 implements Runnable{
private Resouce r;
public Consumer1(Resouce r){
this.r=r;
}
public void run(){
while(true){
r.consumer();
}
}
}
public class TestTc {
public static void main(String[] args) {
Resouce r = new Resouce ();
Producer p = new Producer (r);
Consumer1 c = new Consumer1 (r);
new Thread(p).start();
new Thread(c).start();
}
}
打印结果如下:(帮忙分析一下原因)
Thread-1消费者 --->商品51358
Thread-0生产者 ->商品51358
Thread-1消费者 --->商品51359
Thread-0生产者 ->商品51359
Thread-1消费者 --->商品51360
Thread-0生产者 ->商品51360 |