使用BlockingQueue实现生产者消费者模式

来源:互联网 发布:linux网络书籍 编辑:程序博客网 时间:2024/05/16 17:17
  1. 先上代码
public class BlockingQueueTest {    private static ArrayBlockingQueue<String> QUEUE = new ArrayBlockingQueue<String>(            100, true);    public static void main(String[] args) {        Random random1 = new Random(100);        Thread t1 = new Thread(() -> {            while (true) {                String a = random1.nextInt() + "";                try {                    QUEUE.put(a);                    System.err.println("入列:" + a);                    Thread.sleep(500L);                } catch (InterruptedException e) {                    e.printStackTrace();                    throw new RuntimeException(e);                }            }        });        Thread t2 = new Thread(() -> {            while (true) {                try {                    String a = QUEUE.take().toString();                    System.err.println("出列:" + a);                    System.err.println("队列大小:" + QUEUE.size());                    Thread.sleep(1000L);                } catch (InterruptedException e) {                    e.printStackTrace();                    throw new RuntimeException(e);                }            }        });        t1.start();        t2.start();    }}
  1. BlockingQueue接口中的方法