java多线程之生产者与消费者问题的简单模拟

    技术2022-05-13  3

    //临界资源类class Resource{ private String products[]; int empty,full; int in, out;     public Resource(){     products = new String[10];        empty = 10;        full = 0;     in = 0;     out = 0;    }        public String[] getProducts(){     return products;    }        public synchronized void put(String product){     if(empty == 0){      try{       wait();      }catch(InterruptedException ie){       ie.printStackTrace();      }     }        empty--;     full++;     products[in] = product;     in = (in + 1) % 10;     notifyAll();    }        public synchronized String get(){     String product;     if(full == 0){      try{       wait();      }catch(InterruptedException ie){       ie.printStackTrace();      }     }     full--;     empty++;     product = products[out];     out = (out + 1) % 10;     notifyAll();     return product;    }     }

    //生产者进程类

    class Producer implements Runnable{ private Resource bufarea;//缓冲区  public Producer(Resource buf){  this.bufarea = buf; }  public void run(){  for(int i = 0; i <bufarea.getProducts().length; i++){      String product = "product" + i;      bufarea.put(product);      System.out.println("The producer has produced:" + product);      try{       Thread.sleep(200);      }catch(InterruptedException ie){       ie.printStackTrace();      }        } }}

    //消费者线程类

    class Consumer implements Runnable{ private Resource bufarea;//缓冲区  public Consumer(Resource buf){  this.bufarea = buf;   }  public void run(){  for(int i = 0; i < bufarea.getProducts().length; i++){   String product = bufarea.get();   System.out.println("The consumer has consumed:" + product);   try{    Thread.sleep(500);       }catch(InterruptedException ie){    ie.printStackTrace();   }  } }  }

    public class ProducerConsumer{  public static void main(String args[]){  Resource resource = new Resource();  Producer p = new Producer(resource);  Consumer c = new Consumer(resource);  Thread producer = new Thread(p);  Thread consumer = new Thread(c);  producer.start();  consumer.start(); }}


    最新回复(0)