public class ProCon {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thing thing = new Thing();
Producer p = new Producer(thing);
Consumer s= new Consumer(thing);
new Thread(p).start();
new Thread(s).start();
}
}
class Thing{
private String name=null;
private int counter=1;
private boolean flag=false;
public synchronized void pro(String name)
{
if(flag)
try{this.wait();}catch(Exception e){}
this.name =name+counter++;
System.out.println("生产---"+this.name);
flag=true;
notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exception e){}
System.out.println("消费++++"+this.name);
flag=false;
notify();
}
}
class Producer implements Runnable{
private Thing t=null;
public Producer(Thing t)
{
this.t=t;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
t.pro("商品");
}
}
}
class Consumer implements Runnable{
private Thing t=null;
public Consumer(Thing t)
{
this.t=t;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
t.out();
}
}
}
我想问的就是为什么在run方法里面为什么必须的加while(true){}来访问方法 不然只分别生产和消费一次,那个线程不是一直运行的么。为何还要加while语句了??、求大神指导 |
|