JDK 里面的线程池和Tomcat线程池的区别

java 复制代码
import org.apache.tomcat.util.threads.TaskQueue;
import org.apache.tomcat.util.threads.TaskThreadFactory;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

public class TomcatThreadPoolExecutorTest {

    public static void main(String[] args) throws InterruptedException {
        String namePrefix = "歪歪歪-exec-";
        boolean daemon = true;
        TaskQueue taskqueue = new TaskQueue(300);
        TaskThreadFactory tf = new TaskThreadFactory(namePrefix, daemon, Thread.NORM_PRIORITY);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                150, 60000, TimeUnit.MILLISECONDS, taskqueue, tf);
//        taskqueue.setParent(executor);
        for (int i = 0; i < 305; i++) {
            try {
                executor.execute(() -> {
                    logStatus(executor, "创建任务");
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Thread.currentThread().join();
    }

    private static void logStatus(ThreadPoolExecutor executor, String name) {
        TaskQueue queue = (TaskQueue) executor.getQueue();
        System.out.println(Thread.currentThread().getName() + "-" + name + "-:" +
                "核心线程数:" + executor.getCorePoolSize() +
                "\t活动线程数:" + executor.getActiveCount() +
                "\t最大线程数:" + executor.getMaximumPoolSize() +
                "\t总任务数:" + executor.getTaskCount() +
                "\t当前排队线程数:" + queue.size() +
                "\t队列剩余大小:" + queue.remainingCapacity());
    }
}

队列的使用在日常开发中,特别常见,但是对于队列接口中的一些方法可能使用起来有些疑惑,本文简单记录一下关于Queue接口中几种类似方法的区别。

  • add() 和 offer()
    • add() : 添加元素,如果添加成功则返回true,如果队列是满的,则抛出异常
    • offer() : 添加元素,如果添加成功则返回true,如果队列是满的,则返回false
    • 区别:对于一些有容量限制的队列,当队列满的时候,用add()方法添加元素,则会抛出异常,用offer()添加元素,则返回false
  • remove() 和 poll()
    • remove() : 移除队列头的元素并且返回,如果队列为空则抛出异常
    • poll() : 移除队列头的元素并且返回,如果队列为空则返回null
    • 区别:在移除队列头元素时,当队列为空的时候,用remove()方法会抛出异常,用poll()方法则会返回null
  • element() 和 peek()
    • element() :返回队列头元素但不移除,如果队列为空,则抛出异常
    • peek() :返回队列头元素但不移除,如果队列为空,则返回null
    • 区别 :在取出队列头元素时,如果队列为空,用element()方法则会抛出异常,用peek()方法则会返回null

附上源码以及中文注释:

复制代码
public interface Queue<E> extends Collection<E> {
    /**
     * Inserts the specified element into this queue if it is possible to do so
     * immediately without violating capacity restrictions, returning
     * {@code true} upon success and throwing an {@code IllegalStateException}
     * if no space is currently available.
     * 插入一个具体的元素到队列中如果没有超过容量限制并且返回true。
     * 如果没有队列已满则抛出IllegalStateException
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws IllegalStateException if the element cannot be added at this
     *         time due to capacity restrictions
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this queue
     *         如果插入的对象不对,则会抛出类型转换ClassCastException
     * @throws NullPointerException if the specified element is null and
     *         this queue does not permit null elements
     *         如果插入null,则会抛出空指针异常
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this queue
     * 添加元素,如果添加成功则返回true,如果队列是满的,则抛出异常
     */
    boolean add(E e);

    /**
     * Inserts the specified element into this queue if it is possible to do
     * so immediately without violating capacity restrictions.
     * When using a capacity-restricted queue, this method is generally
     * preferable to {@link #add}, which can fail to insert an element only
     * by throwing an exception.
     * 插入一个具体的元素到队列中如果没有超过容量限制并且返回true。
     * 如果没有队列已满则返回false。
     * 当使用一个有容量限制的队列时,建议使用该方法offer(),因为使用add()方法当队列满时会
     * 直接抛出异常,则offer()方法则返回false
     *
     * @param e the element to add
     * @return {@code true} if the element was added to this queue, else
     *         {@code false}
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this queue
     * @throws NullPointerException if the specified element is null and
     *         this queue does not permit null elements
     * @throws IllegalArgumentException if some property of this element
     *         prevents it from being added to this queue
     * 添加元素,如果添加成功则返回true,如果队列是满的,则返回false
     */
    boolean offer(E e);

    /**
     * Retrieves and removes the head of this queue.  This method differs
     * from {@link #poll poll} only in that it throws an exception if this
     * queue is empty.
     *
     * @return the head of this queue
     * @throws NoSuchElementException if this queue is empty
     * 移除队列头的元素并且返回,如果队列为空则抛出异常
     */
    E remove();

    /**
     * Retrieves and removes the head of this queue,
     * or returns {@code null} if this queue is empty.
     *
     * @return the head of this queue, or {@code null} if this queue is empty
     * 移除队列头的元素并且返回,如果队列为空则返回null
     */
    E poll();

    /**
     * Retrieves, but does not remove, the head of this queue.  This method
     * differs from {@link #peek peek} only in that it throws an exception
     * if this queue is empty.
     *
     * @return the head of this queue
     * @throws NoSuchElementException if this queue is empty
     * 返回队列头元素但不移除,如果队列为空,则抛出异常
     */
    E element();

    /**
     * Retrieves, but does not remove, the head of this queue,
     * or returns {@code null} if this queue is empty.
     *
     * @return the head of this queue, or {@code null} if this queue is empty
     * 返回队列头元素但不移除,如果队列为空,则返回null
     */
    E peek();
}

作者:曾泽浩

链接:https://www.jianshu.com/p/c41053d16713/

来源:简书

简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

相关推荐
知兀5 分钟前
【MybatisPlus】后端用枚举类,数据库用tinyint,存在枚举类型转换
java
StockTV7 分钟前
印度股票实时数据 NSE和BSE的实时行情、K 线及指数数据
java·开发语言·spring boot·python
User_芊芊君子9 分钟前
【OpenAI 把 AI 玩明白了】:自主推理 + 动态知识图谱,这 4 个技术突破要颠覆行业
java·人工智能·知识图谱
c++之路42 分钟前
C++20概述
java·开发语言·c++20
Championship.23.241 小时前
Linux Top 命令族深度解析与实战指南
java·linux·服务器·top·linux调试
橘子海全栈攻城狮1 小时前
【最新源码】养老院系统管理A013
java·spring boot·后端·web安全·微信小程序
逻辑驱动的ken1 小时前
Java高频面试考点18
java·开发语言·数据库·算法·面试·职场和发展·哈希算法
冷雨夜中漫步2 小时前
Claude Code源码分析——Claude Code Agent Loop 详细设计文档
java·开发语言·人工智能·ai
直奔標竿2 小时前
Java开发者AI转型第二十六课!Spring AI 个人知识库实战(五)——联网搜索增强实战
java·开发语言·人工智能·spring boot·后端·spring
one_love_zfl2 小时前
java面试-微服务组件篇
java·微服务·面试