LinkedBlockingQueue中的put/take方法简单使用

在一些小项目中有时候会使用LinkedBlockingQueue作为本地的缓存队列,LinkedBlockingQueue中有两个方法比较常使用,分别为put()和take()。

put()方法向队列中生产数据,当队列满时,线程阻塞

take()方法从队列中消费数据,当队列为空是,线程阻塞

简单的使用例子:

/**
     * 阻塞队列
     */
    private static LinkedBlockingQueue frameTaskQueue = new LinkedBlockingQueue(500);

    /**
     * <将消息放入队列中,若当前队列满,线程阻塞>
     *
     * @param msg msg
     * @throws
     */
    public static void produce(String msg) throws InterruptedException {
        LOGGER.info("start to produce msg.");
        frameTaskQueue.put(msg);
    }

    /**
     * <消费队列中数据,若当前队列无数据,线程阻塞>
     *
     * @return 消息
     * @throws
     */
    public static String consume() throws InterruptedException {
        return (String)frameTaskQueue.take();
    }

 


版权声明:本文为wangchaox123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。