java创建线程池的4种方式之队例LinkedBlockingQueue(七)

本文详细介绍了Java中使用LinkedBlockingQueue进行线程安全的队列操作,包括生产者和消费者模式下的元素添加(add, offer, put)及获取(poll, peek, take)方法的区别与应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用方法:

一、添加元素

1、add 方法:如果队列已满,报java.lang.IllegalStateException: Queue full 错误

2、offer 方法:如果队列已满,程序正常运行,只是不再新增元素

3、put 方法:如果队列已满,阻塞

二、取元素

1、poll 方法:弹出队顶元素,队列为空时返回null

2、peek 方法:返回队列顶元素,但顶元素不弹出,队列为空时返回null

3、take 方法:当队列为空,阻塞

package com.xuecheng.manage_cms;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>();
        new Customer(queue).start();
        new Product(queue).start();
    }

    //生产者
    static class Product extends Thread{
        LinkedBlockingQueue<Integer> queue;
        public Product(LinkedBlockingQueue<Integer> queue){
            this.queue = queue;
        }
        @Override
        public void run(){
            while(true){
                int rand = new Random().nextInt(1000);
                System.out.println("生产了一个产品:"+rand);
                System.out.println("等待三秒后运送出去...");
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //offer() 往queue里放一个element后立即返回,如果碰巧这个element被另一个thread取走了,offer方法返回true,认为offer成功;否则返回false。
//                boolean offer = queue.offer(rand);
//                System.out.println(offer);
                //put put() 往queue放进去一个element以后就一直wait直到有其他thread进来把这个element取走。
                try {
                    queue.put(rand);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("产品生成完成:"+rand);
            }
        }
    }
    //消息者
    static class Customer extends Thread{
        LinkedBlockingQueue<Integer> queue;
        public Customer(LinkedBlockingQueue<Integer> queue){
            this.queue = queue;
        }
        @Override
        public void run(){
            while(true){
                try {
                    System.out.println("消费了一个产品:"+queue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("------------------------------------------");
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值