java生产者消费者例子

可以调整生产者生产速度和消费者消费速度看结果,原文:

http://blog.csdn.net/andyxhua/article/details/2043855

 

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


public class BlockQueueSample {

    BlockingQueue<String> resource = new LinkedBlockingQueue<>(10);
    AtomicInteger i = new AtomicInteger();
    boolean exit = false;

    public BlockQueueSample() {
        Thread consumer = new Thread(new Consumer());
        Thread producer = new Thread(new Producer());
        consumer.start();
        producer.start();
    }

    public void exit() {
        this.exit = true;
    }

    public static void main(String[] args) {
        BlockQueueSample sample = new BlockQueueSample();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return;
        }
        sample.exit();
        System.exit(0);
    }

    class Consumer implements Runnable {

        @Override
        public void run() {
            while (!exit) {
                try {
                    System.out.println("Consumer take:" + resource.take());
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    }

    class Producer implements Runnable {

        @Override
        public void run() {
            while (!exit) {
                String r = "Resource" + i.getAndIncrement();
                System.out.println("Producer put:" + r);
                try {
                    resource.put(r);
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    return;
                }
            }
        }
    }
}
posted @ 2012-10-19 14:39  Leo Forest  阅读(364)  评论(0编辑  收藏  举报