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

}
posted on 2016-04-19 10:59  Android9527  阅读(175)  评论(0编辑  收藏  举报