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

初学者:多线程碰到的纠结问题
首先,请看我的代码:
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(this){
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))) ;
System.out.println(goods.size());
}
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(this){
consumption();
}
}
catch(Exception err){err.printStackTrace();}
}
public void consumption(){//消费
System.out.println("coming ! the current thread is "+Thread.currentThread().getName());
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 !");
else{
Goods g;
int i = goods.size() ;
while( 0 != i ){
g = (Goods)goods.get(i-1);
g.displays();
i -- ;
}
}
}
private List<Goods> goods;
}

class Goods{//商品类
private int id ;
private String name = "goods";
private double price ;
public Goods(int id , String name , double price){this.id = id ; this.name = this.name+name ; this.price = price ;}