Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29944984
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2009-07-20 17:07:14

1.作业分Producwer,Consumer,Space,Apple,Test5个类编写。

2.Space为中转存储空间,Apple为标记生产物品。

3.所有类都存放于sycnchronized包内。

***********************************************************

package sycnchronized;
//产品标识
public class Apple {
int id;
public Apple(int id){
  this.id=id;
}
// public String toString(){
//  return ""+id;
// }
}

…………………………………………………………

package sycnchronized;
//产品的存储空间
public class Space {
  Apple ap[]=new Apple[10];
  int index=0;
  //产品存入
  public synchronized void push(Apple AP) {
  
   while(index==ap.length){
    try {
    
     this.wait();
    
    } catch (InterruptedException e) {
     // TODO 自动生成 catch 块
     e.printStackTrace();
    }
   }
   ap[index]=AP;
   index++;
   this.notify();
  }
// 产品的取出
  public synchronized Apple pop(){
   while (index==0){
    try {
    
     this.wait();
    
    } catch (InterruptedException e) {
     // TODO 自动生成 catch 块
     e.printStackTrace();
    }
   }
   index--;
   this.notify();
   return ap[index];
  }


}
……………………………………………………………………

package sycnchronized;
//摘苹果
public class Producer implements Runnable{
     Space sp=new Space();
     Producer (Space sp){
      this.sp=sp;
     }
public void run() {
  for(int i=0;i<100;i++){
   Apple Ap=new Apple(i);
   sp.push(Ap);
   System.out.println("摘了"+(i+1)+"个苹果!");
   try {
    Thread.sleep(50);
   } catch (InterruptedException e) {
    // TODO 自动生成 catch 块
    e.printStackTrace();
   }
  }
 
}

}
………………………………………………………………………

package sycnchronized;
//吃苹果
public class Consumer implements Runnable {
   Space sp=new Space();
   Consumer(Space sp){
    this.sp=sp;
   }
public void run() {
  for(int i=0;i<100;i++){
   Apple Ap=sp.pop();
  
   System.out.println("吃掉了"+(i+1)+"个苹果!");
   System.out.println();
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO 自动生成 catch 块
    e.printStackTrace();
   }
  }
}

}
……………………………………………………………………

package sycnchronized;
//测试
public class Test {
public static void main(String[] args) {
Space sp=new Space();
Producer pd=new Producer(sp);
Consumer cs=new Consumer(sp);
new Thread(pd).start();
new Thread(cs).start();

}
}
阅读(2426) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~