HardBirch

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

时间:09-09-20 栏目:安卓学习笔记 作者:张飞不张,文采横飞 评论:0 点击: 1,317 次

//临界资源类
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();
 }
}

声明: 本文由( 张飞不张,文采横飞 )原创编译,转载请保留链接: java多线程之生产者与消费者问题的简单模拟

java多线程之生产者与消费者问题的简单模拟:等您坐沙发呢!

发表评论


QQ群互动

Linux系统与内核学习群:194051772

WP建站技术学习交流群:194062106

魔豆之路QR

魔豆的Linux内核之路

魔豆的Linux内核之路

优秀工程师当看优秀书籍

优秀程序员,要看优秀书!

赞助商广告

友荐云推荐