//为什么,会没有结果,死锁吗?
class Resourse{
private String name;
private int num = 1;
private boolean flag;
public synchronized void set(String name){
if(flag){
try{this.wait();} catch(InterruptedException e) {}
}
else{
this.name = name+num;
num++;
System.out.println(Thread.currentThread().getName()+"***生产者***"+this.name);
flag = true;
this.notify();
}
}
public synchronized void get(){
if(flag){
try{this.wait();}catch(InterruptedException e){}
}
else{
System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
flag = false;
this.notify();
}
}
}
class Produce implements Runnable{
Resourse r;
public Produce(Resourse r){
this.r = r;
}
public void run(){
while(true){
r.set("馒头");
}
}
}
class Consumer implements Runnable{
Resourse r;
public Consumer(Resourse r){
this.r = r;
}
public void run(){
while(true){
r.get();
}
}
}
public class Show{
public static void main(String[] args){
Resourse r = new Resourse();
Produce p = new Produce(r);
Consumer c = new Consumer(r);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
|