java多线程交互案例

设计两个线程,完成消费者购买商品和生产者生产商品。

首先定义一个商品类:

public class Product {
 private int id;
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String toString(){\\重写tostring方法
  return "ID是"+id+"的产品。";
 }
}

设置一个仓库,用来放置生产的商品

 public class storage {
 Product [] ps=new Product[10];//此处设置了仓库的容量,只能放置10个商品
 int index=0;
 public synchronized void push(Product p) {
  while(index==ps.length){
   try {
    this.wait();//当仓库已满时,暂停商品的生产,等待消费者购买
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   } 
  }
  ps[index]=p;
  index++;
  this.notifyAll();//通知消费者仓库中已有商品,可以购买了
 }
 public synchronized Product pop() {
  while(index==0){
   try {
    this.wait();//当仓库没有商品时,消费者暂停购买,等待生产者生产
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
  }
  index--;
  Product p=ps[index];
  this.notifyAll();//通知生产者仓库未满,可以继续生产了
  return p;
  
 }
}

定义一个生产者类

 public class Producer implements Runnable{//实现runnable接口
 private storage  store=null;
 public Producer(storage store){//定义含参的构造方法
  this.store=store;
 }
 public void run() {重写run方法
  int i=0;
  while(true){
   Product p=new Product();
   i++;
   p.setId(i);
   store.push(p);//调用仓库类的方法实现生产
  } 
 }
}

定义一个消费者类:

public class Customer implements Runnable{
 private storage store=null;
 public Customer(storage store){
  this.store=store;
 }
 public void run() {
  for(int i=0;i<1000;i++){
   Product p=store.pop();//调用仓库类的方法实现购买
   System.out.println("消费者购买了"+p);
  }  
 }
}

最后写一个测试类进行测试

public class test {
 public static void main(String[] args) {
  storage store=new storage();
  Producer p=new Producer(store);
  Customer c=new Customer(store);
  Thread t1=new Thread(p);//创建线程对象
  Thread t2=new Thread(c);
  t1.start();//线程启动
  t2.start();
 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值