用java5提供的阻塞队列实现生产者消费者示例

到了java5,实现数据同步就更简单了。甚至不需要写synchronized和wait/notify。

因为java5提供了阻塞队列,即:

java.util.concurrent.BlockingQueue

用它写一个单消费者和单生产者的示例,基本如下:


class MyProducer implements Runnable {

    private static int count;

    private BlockingQueue<String> queue;

    public MyProducer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                this.queue.put("s" + count++);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                Thread.sleep(1000 * 2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

class MyConsumer implements Runnable {

    private BlockingQueue<String> queue;

    public MyConsumer(BlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("c ->" + queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

十分简明。

运行效果如下:

image

示例见:

http://easymorse.googlecode.com/svn/tags/thread.demo-1.3/

PDF格式打印機    发送文章为PDF   

这篇文章上的评论的 RSS feed TrackBack URI

Leave a Reply