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/

来源:简书

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

相关推荐
Mryan200528 分钟前
解决GraalVM Native Maven Plugin错误:JAVA_HOME未指向GraalVM Distribution
java·开发语言·spring boot·maven
VX_CXsjNo138 分钟前
免费送源码:Java+SSM+Android Studio 基于Android Studio游戏搜索app的设计与实现 计算机毕业设计原创定制
java·spring boot·spring·游戏·eclipse·android studio·android-studio
ylfhpy44 分钟前
Java面试黄金宝典33
java·开发语言·数据结构·面试·职场和发展·排序算法
乘风!1 小时前
Java导出excel,表格插入pdf附件,以及实现过程中遇见的坑
java·pdf·excel
小小鸭程序员1 小时前
Vue组件化开发深度解析:Element UI与Ant Design Vue对比实践
java·vue.js·spring·ui·elementui
南宫生2 小时前
Java迭代器【设计模式之迭代器模式】
java·学习·设计模式·kotlin·迭代器模式
seabirdssss2 小时前
通过动态获取项目的上下文路径来确保请求的 URL 兼容两种启动方式(IDEA 启动和 Tomcat 部署)下都能正确解析
java·okhttp·tomcat·intellij-idea
kill bert2 小时前
第30周Java分布式入门 消息队列 RabbitMQ
java·分布式·java-rabbitmq
穿林鸟3 小时前
Spring Boot项目信创国产化适配指南
java·spring boot·后端
此木|西贝4 小时前
【设计模式】模板方法模式
java·设计模式·模板方法模式