基于Java阻塞队列实现生产者与消费者模式

java 阻塞队列实现生产者与消费者模式

public class BlockingTest {
    public static void main(String[] args) {
        ArrayBlockingQueue arrayBlockingQueue = new ArrayBlockingQueue(100);

        Consumer consumer = new Consumer(arrayBlockingQueue);
        Produce produce = new Produce(arrayBlockingQueue);
        consumer.start();
        produce.start();

    }

    static class Consumer extends Thread {

        ArrayBlockingQueue arrayBlockingQueue = null;

        public Consumer(ArrayBlockingQueue arrayBlockingQueue) {
            this.arrayBlockingQueue = arrayBlockingQueue;
        }

        @Override
        public void run() {
            int consumerValue;
            while (true) {
                try {
                    consumerValue = arrayBlockingQueue.take();
                    System.out.println(String.format("消费者消费了一个元素【%s】", consumerValue));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    static class Produce extends Thread {
        ArrayBlockingQueue arrayBlockingQueue;

        public Produce(ArrayBlockingQueue arrayBlockingQueue) {
            this.arrayBlockingQueue = arrayBlockingQueue;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                arrayBlockingQueue.add(i);
                System.out.println(String.format("生产者生产了一个元素【%s】", i));
            }
        }
    }
}

你可能感兴趣的:(Java)