为什么生产者线程产生更多的一个项目,即使我也设置容量为1

时间:2017-12-05 17:25:48

标签: java concurrency

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

public class ProducerAndConsummerUsingBlockingqueue {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>(1);
        Thread t1 = new Thread(new Producerqueue(blockingQueue));
        Thread t2 = new Thread(new Consumner(blockingQueue));
        t1.start();
        t2.start();

    }

}

class Producerqueue implements Runnable {

    BlockingQueue<Integer> blockingQueue;

    public Producerqueue(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 1; i <= 10; i++) {
            try {
                System.out.println("produced item " + i);
                blockingQueue.put(i);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

class Consumner implements Runnable {
    BlockingQueue<Integer> blockingQueue;

    public Consumner(BlockingQueue<Integer> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            try {
                System.out.println("consumed item " + blockingQueue.take());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}

即使我为生产者设置了容量1,然后也是如下的输出。我不理解生产项目是否超过1甚至我设置容量为1

produced item 1
produced item 2
consumed item 1
produced item 3
consumed item 2
produced item 4
consumed item 3
produced item 5
consumed item 4
produced item 6
consumed item 5
produced item 7
consumed item 6
produced item 8
consumed item 7
produced item 9
consumed item 8
produced item 10
consumed item 9
consumed item 10

1 个答案:

答案 0 :(得分:0)

容量表示队列一次可容纳多少项。此外,您设置Producerqueue的方式将在尝试将新项目放入队列之前打印邮件。这意味着您将看到生成的第2项之类的消息,但blockingQueue.put(i);语句将阻塞,直到它可以在不超过其容量的情况下向队列中添加新项目。

简而言之,您的生产者在将新项目添加到队列之前打印其消息。