使用BlockingQueue阻塞队列实现生产者与消费者

BlockingQueue阻塞式队列

  1. 主要实现类:
    使用BlockingQueue阻塞队列实现生产者与消费者_第1张图片
  2. 使用有界队列ArrayBlockingQueue实现生产者与消费者;
public class ArrayBlockingQueueTest {
    private static ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue(10);
    @Test
    public void test() {
        Runnable add = () -> {
            for (int i = 0; i < 100; i++) {
                try {
                    queue.put(i);
                    System.out.println(Thread.currentThread().getName() + ":" + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable delete = () -> {
            for (int i = 0; i < 100; i++) {
                try {
                    Integer poll = queue.take();
                    System.out.println(Thread.currentThread().getName() + ":" + poll);
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread = new Thread(add, "add");
        Thread thread1 = new Thread(delete, "delete1");
        Thread thread2 = new Thread(delete, "delete2");
        Thread thread3 = new Thread(delete, "delete3");
        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();
        try {
            thread.join();
            while (queue.size() > 0) {
            }
        } catch (InterruptedException e) {
        }
    }
}
  1. 上述代码定义了ArrayBlockingQueue的队列大小为10,也就是说生产者生产满10个物品就会进入阻塞状态,直到消费者进行消费才可以继续生产;

你可能感兴趣的:(java并发,多线程,队列,queue,java)