package day_nov_14;
class Resouse{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(String name){
if(flag)
try {wait();} catch (InterruptedException e) {e.printStackTrace();}
this.name=name+count;
count++;
System.out.println(Thread.currentThread().getName()+".....生产者......生产者生成了"+this.name);
flag=true;
notify();
}
public synchronized void out(){
if(!flag);
try {wait();} catch (InterruptedException e) {e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"==========消费者吃了====吃了"+this.name);
flag=false;
notify();
}
}
class Producer implements Runnable{
private Resouse r;
Producer (Resouse r){
this.r=r;
}
public void run() {
for(int x=1;x<=50;x++){
r.set("饭");
}
}
}
class Consumer implements Runnable{
private Resouse r;
Consumer (Resouse r){
this.r=r;
}
public void run() {
for(int x=1;x<=50;x++){
r.out();
}
}
}
public class ProduceVsConsumer {
public static void main(String[] args) {
Resouse re=new Resouse();
Producer p=new Producer(re);
Consumer c=new Consumer(re);
Thread t1=new Thread(c);
Thread t2=new Thread(p);
t1.start();
t2.start();
}
}
最后两个线程开启的顺序不一样,运行结果就不一样。。。。 |