java多线程交互案例

来源:互联网 发布:金字塔量化交易软件 编辑:程序博客网 时间:2024/06/05 12:02
设计两个线程,完成消费者购买商品和生产者生产商品。

首先定义一个商品类:

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(); }}


原创粉丝点击