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

生产者消费者模型

时间:2016-04-19 11:34:53      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:

1.篮子

package queue.test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Basket {

    BlockingQueue<String> basket = new LinkedBlockingQueue<String>(3);
    
    public void produce() throws InterruptedException
    {
        basket.put("apple");
    }
    
    public String consume() throws InterruptedException
    {
        return basket.take();
    }
}

2.生产者

package queue.test;

public class Producer implements Runnable{

    private String instance;
    private Basket basket;

    public Producer(String instance, Basket basket) {
        super();
        this.instance = instance;
        this.basket = basket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true)
        {
            System.out.println("produce apple start-"+instance);
            try 
            {
                basket.produce();
                System.out.println("produce apple end-"+instance);
                Thread.sleep(300);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

3.消费者

package queue.test;

public class Consumer implements Runnable{

    private String instance;
    private Basket basket;
    
    public Consumer(String instance, Basket basket) {
        super();
        this.instance = instance;
        this.basket = basket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(true)
        {
            System.out.println("consumer start-"+instance);
            try {
                basket.consume();
                
                System.out.println("consumer end-"+instance);
                
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

3.测试

package queue.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class QueueTest {

    public static void main(String[] args) {
        Basket basket = new Basket();
        
        Producer p1 = new Producer("p1", basket);
        Producer p2 = new Producer("p2", basket);
        Consumer c = new Consumer("c1", basket);
        
        ExecutorService pool = Executors.newCachedThreadPool();
        pool.submit(p1);
        pool.submit(p2);
        pool.submit(c);
    }

}

生产者消费者模型

标签:

原文地址:http://www.cnblogs.com/Android9527/p/5407340.html

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