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

常用方法:

一、添加元素

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 queue = new LinkedBlockingQueue();
        new Customer(queue).start();
        new Product(queue).start();
    }

    //生产者
    static class Product extends Thread{
        LinkedBlockingQueue queue;
        public Product(LinkedBlockingQueue 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 queue;
        public Customer(LinkedBlockingQueue queue){
            this.queue = queue;
        }
        @Override
        public void run(){
            while(true){
                try {
                    System.out.println("消费了一个产品:"+queue.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("------------------------------------------");
            }
        }
    }
}

你可能感兴趣的:(线程)