/**帮我改一下这道程序,里面有少许的错误但是一直
*找不出来,请大虾帮我指点一下,为什么要那样做
*/
public class Li9_6 {

/**
 * @param args
 */
public static void main(String[] args) {

// TODO 自动生成方法存根
Store s= new Store();
Producer p2= new Producer(s,3);
Consumer c2= new Consumer(s,3);
p2.start();
c2.start();
}

}
class Producer extends Thread{
 
 private Store store;
 private int num;
 
// 构造方法
 public Producer(Store s,int num) {
 store=s;
 this.num=num;  
 }
 
// 线程体
 public void run() {
 for(int i=0;i<10;i++) {
 store.put(i);        //放i到store对象
 
 System.out.println("Producer#"+this.num+"put:"+i);     //显示放数i
 
 try {
 sleep((int)(Math.random()*100));         //休眠0~100
 }catch(InterruptedException e) {}
 
 }
 }          
}//生产者Producer线程
 
class Consumer extends Thread{
 private Store store;
 private int num;
 
// 构造方法
 public Consumer(Store s,int num) {
 store =s;
 this.num=num;
 
 }
 
// 线程体
 public void run() {
 int value=0;
 for(int i=0;i<10;i++) {
 value=store.get();//从store对象取值
 System.out.println("Consumer#"+this.num+"got:"+value);
 }
 }
}//Consumer线程class Store{
 private int seq;
 private boolean available=false;
 public synchronized int get() {
 
 while (available==false) {
 
 try {
 wait();
 
 }
 catch(InterruptedException e) {
 
 }
 }
 
 available=false;
 notify();
 return seq;
 }
 
 public synchronized void put(int value) {
 
 while(available==true) {
 try {
 wait();
 }
 catch(InterruptedException e) {
 
 }
 }
 
 seq=value;
 available=true;
 notify();  
 }
 }
 
 
 
 
 

解决方案 »

  1.   

    store的seq的值在2个线程同时操作时,get() 方法返回的 seq 不正确。
      

  2.   

    这是生产者和消费者问题,这道程序在class store和class Consumer extends Thread{ 和class Producer extends Thread{ 中分别提示"已定义类型store","已定义类型Consumer","已定义类型Producer"。究竟哪里错了啊,想了很久都没改过来,帮帮忙吧