日期:2014-05-20  浏览次数:20799 次

关于java的wait()的问题
首先请看代码:

package clone;

/**
 * 生产者与消费者的问题
 */
import java.util.*;
public class Run{
public static void main(String[]args){
Producer p = new Producer();
Consumer c = new Consumer();
new Thread(p,"p").start();//start时就会调用produce()
new Thread(c,"c").start();//start时就会调用consumption()
}
}

class Producer implements Runnable{
public Producer(){
if( null == goods ) goods = new ArrayList<Goods>();
}
@Override
public void run(){
try{
synchronized(Run.class){
if( 5 > goods.size() )
for( int i=goods.size() ; i<5 ; i++)
produce();
}
}
catch(Exception err){err.printStackTrace();}
}
public void produce() throws Exception{//生产
System.out.println("coming ! the current thread is "+Thread.currentThread().getName());
int size = goods.size()+1 ;
String name = String.valueOf(size);
goods.add(new Goods(size , name ,Double.parseDouble(name))) ;
}
private static List<Goods> goods;
public static List<Goods> obtainedGoods(){ 
System.out.println(Thread.currentThread().getName()+":"+goods.size());return goods ; }
}

class Consumer implements Runnable{
@Override
public void run(){
try{
synchronized(Run.class){
goods = Producer.obtainedGoods();
if( null == goods ) System.out.println(Thread.currentThread().getName()+":"+"do not have this kind of goods !");
if( 0 == goods.size() ) 
{
System.out.println(Thread.currentThread().getName()+":"+"this goods have been done not have ! we must wait for produce");
this.wait();
}
consumption();
this.notify();
}
}
catch(Exception err){
err = new IllegalMonitorStateException(Thread.currentThread().getName());
err.printStackTrace();
}
}
public void consumption() throws Exception{//消费
System.out.println("coming ! the current thread is "+Thread.currentThread().getName());
Goods g;
int i = goods.size() ;
while( 0 != i ){
g = (Goods)goods.get(i-1);