码迷,mamicode.com
首页 > 其他好文 > 详细

生产者消费者问题

时间:2017-05-14 22:53:22      阅读:274      评论:0      收藏:0      [点我收藏+]

标签:main   rri   rod   nbsp   logs   while   runnable   start   color   

import java.util.*;
public class ProducerConsumerTest{
    final int BUFFER_SIZE=10;//缓冲区最大值
    Queue<Integer> queue;//共享缓冲队列
    public ProducerConsumerTest(){
        queue=new LinkedList<Integer>();
    }
    public static void main(String[] args){
        ProducerConsumerTest PC=new ProducerConsumerTest();
        int count=100;
        System.out.println("开始生产消费了哦");
        while(count-->0){
            new Thread(PC.new Producer()).start();
            new Thread(PC.new Consumer()).start();
        }
        
    }
    class Consumer implements Runnable{
        @Override
        public void run() {
            synchronized(queue){
                if(queue.size()==0){
                    try {
                        queue.wait();//释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    int x=queue.remove();
                    System.out.println("消费 :"+x);
                    queue.notify();//唤醒生产者
                }
                
            }
        }
    }
    class Producer implements Runnable{

        @Override
        public void run() {
            synchronized(queue){
                if(queue.size()==BUFFER_SIZE){
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }    
                }else{
                    int x=queue.size()+1;
                    queue.add(x);
                    System.out.println("生产 :"+x);
                    queue.notify();
                }
            }
        }
        
    }
    
}

 

生产者消费者问题

标签:main   rri   rod   nbsp   logs   while   runnable   start   color   

原文地址:http://www.cnblogs.com/wqkant/p/6854148.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!