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/

来源:简书

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

相关推荐
吾日三省吾码2 小时前
JVM 性能调优
java
弗拉唐3 小时前
springBoot,mp,ssm整合案例
java·spring boot·mybatis
oi774 小时前
使用itextpdf进行pdf模版填充中文文本时部分字不显示问题
java·服务器
少说多做3434 小时前
Android 不同情况下使用 runOnUiThread
android·java
知兀4 小时前
Java的方法、基本和引用数据类型
java·笔记·黑马程序员
蓝黑20205 小时前
IntelliJ IDEA常用快捷键
java·ide·intellij-idea
Ysjt | 深5 小时前
C++多线程编程入门教程(优质版)
java·开发语言·jvm·c++
shuangrenlong5 小时前
slice介绍slice查看器
java·ubuntu
牧竹子5 小时前
对原jar包解压后修改原class文件后重新打包为jar
java·jar