JavaEE 初阶篇-深入了解线程池(线程池创建、线程池如何处理任务)

🔥博客主页: 【小扳_-CSDN博客】
❤感谢大家点赞👍收藏⭐评论✍

文章目录

        1.0 线程池概述

        1.1 线程池的优点

        1.2 不使用线程池的问题

        1.3 线程池的工作原理图

        1.4 如何创建线程池? 

        2.0 通过 ThreadPoolExecutor 类自定义创建线程池

        2.1 ThreadPoolExecutor 构造器

        3.0 线程池处理 Runnable 任务

        3.1 通过 void execute(Runnable command) 方法

        3.2 通过 void shutdown() 方法

        3.3 通过 List shutdownNow() 方法

        3.4 临时线程什么时候创建?

        3.5 什么时候会开始拒绝新任务?

        4.0 线程池处理 Callable 任务

        4.1 通过 submit() 方法

        5.0 通过 Executors 工具类创建出线程池

        5.1 通过 Executors.newFixedThreadPool(int nThreads) 方法来创建线程池

        5.2 通过 Executors.newCachedThreadPool() 方法来创建线程池

        5.3 通过 Eexcutors.newSingleThreadExecutor() 方法来创建线程池

        6.0 新任务拒绝策略

        6.1 AbortPolicy(默认策略,直接抛出异常)

        6.2 DiscardPolicy(直接丢弃任务)

        6.3 CallerRunsPolicy(由调用线程执行任务)

        6.4 DiscardOldestPolicy(丢弃队列中最旧的任务)


        1.0 线程池概述

        线程池是一种重要的并发编程机制,用于管理和复用线程,以提高应用程序的性能和资源利用率。

        线程池就是一个可以复用线程的技术。

        1.1 线程池的优点

        1)降低线程创建和销毁的开销。通过重用线程从而减少频繁创建和开销线程所带来的性能损耗。

        2)控制并发线程数量。通过设定线程池的大小和配置,可以限制并发线程的数量,避免系统资源耗尽。

        1.2 不使用线程池的问题

        假设用户发起一个请求,后台就需要创建一个新线程来处理,下次新任务来了肯定又要创建新线程处理的,而创建新线程的开销是很大的,并且请求过多时,肯定会产生大量的线程出来,这样会严重影响系统的性能。

        1.3 线程池的工作原理图

        1.4 如何创建线程池? 

        常见的创建线程池的方式有两种:

        1)通过已经实现 ExecutorService 接口的 ThreadPoolExecutor 类来创建出线程池。

        2)通过 Executors 工具类创建出线程池。

 

        2.0 通过 ThreadPoolExecutor 类自定义创建线程池

        可以直接使用 ThreadPoolExecutor 类来创建自定义的线程池,通过指定核心线程数、最大线程数、工作队列等参数来满足特定的需求。这种方法更灵活,可以根据具体场景进行定制化配置。

        2.1 ThreadPoolExecutor 构造器

        1)参数一:corePoolSize:指定线程池的核心线程的数量。

        2)参数二:maximumPoolSize:指定线程池的最大线程数量。

        3)参数三:keepAliveTime:指定临时线程的存活时间。

        4)参数四:unit:指定临时线程的存活时间单位(秒、分、时、天)。

        5)参数五:workQueue:指定线程池的任务队列。

        6)参数六:threadFactory:指定线程池的线程工厂(创建线程的地方)。

        7)参数七:handler:指定线程池的任务拒绝策略(线程都在忙,任务队列也满的时候,新任务来了该怎么处理)。

具体创建线程池代码如下:

import java.util.concurrent.*;
public class CreateThreadPoolExecutor {public Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量5,//最大线程数量8,//临时线程存活时间TimeUnit.SECONDS,//临时线程存活时间单位new ArrayBlockingQueue<>(4),//创建任务队列,最大存放任务数量为4Executors.defaultThreadFactory(),//线程工厂,//用到了Executors工具类来创建默认线程工厂new ThreadPoolExecutor.AbortPolicy());//拒绝策略,默认策略:抛出异常}

        

        3.0 线程池处理 Runnable 任务

        线程池通过执行 Runnable 任务来实现多线程处理。将实现 Runnable 接口的任务提交给线程池,线程池会根据配置的参数调度任务执行。核心线程数内的任务会立即执行,超出核心线程数的任务会被放入任务队列中。如果任务队列已满,且线程数未达到最大线程数,线程池会创建新线程执行任务。线程池管理线程的生命周期,重用线程以减少线程创建和销毁的开销。

ExecutorService 的常用方法:

        3.1 通过 void execute(Runnable command) 方法

        将 Runnable 类型的任务交给线程池,线程池就会自动创建线程,自动执行 run() 方法且自动启动线程。

代码如下:

import java.util.concurrent.*;
public class CreateThreadPoolExecutor {public static void main(String[] args) {Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量5,//最大线程数量8,//临时线程存活时间TimeUnit.SECONDS,//临时线程存活时间单位new ArrayBlockingQueue<>(4),//创建任务队列,最大存放任务数量为4Executors.defaultThreadFactory(),//线程工厂,//用到了Executors工具类来创建默认线程工厂new ThreadPoolExecutor.AbortPolicy());//拒绝策略,默认策略:抛出异常//定义出Runnable类型的任务MyRunnable myRunnable1 = new MyRunnable();MyRunnable myRunnable2 = new MyRunnable();//将该任务提交给线程池threadPool.execute(myRunnable1);threadPool.execute(myRunnable2);}
}
class  MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "正在执行");}
}

运行结果:

        需要注意的是,任务执行完毕之后,线程池中的线程不会销毁,还在继续运行中

        3.2 通过 void shutdown() 方法

        等待全部任务执行完毕后,再关闭线程池。想要手动关闭线程池中的线程,可以用该方法,等待全部任务都执行后才会关闭。

代码如下:

import java.util.concurrent.*;
public class CreateThreadPoolExecutor {public static void main(String[] args) {Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量5,//最大线程数量8,//临时线程存活时间TimeUnit.SECONDS,//临时线程存活时间单位new ArrayBlockingQueue<>(4),//创建任务队列,最大存放任务数量为4Executors.defaultThreadFactory(),//线程工厂,//用到了Executors工具类来创建默认线程工厂new ThreadPoolExecutor.AbortPolicy());//拒绝策略,默认策略抛出异常//定义出Runnable类型的任务MyRunnable myRunnable1 = new MyRunnable();MyRunnable myRunnable2 = new MyRunnable();//将该任务提交给线程池threadPool.execute(myRunnable1);threadPool.execute(myRunnable2);//当全部任务都执行结束后,才会关闭((ThreadPoolExecutor) threadPool).shutdown();}
}
class  MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "正在执行");}
}

运行结果:

        3.3 通过 List<Runnable> shutdownNow() 方法

        立刻关闭线程池,停止正在执行的任务,并返回队列中未执行的任务。先比较与以上的方法,当前的方法就很“激进”了。不管任务结束与否,都会关闭线程池中的线程。

代码如下:

import java.util.List;
import java.util.concurrent.*;
public class CreateThreadPoolExecutor {public static void main(String[] args) {Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量5,//最大线程数量8,//临时线程存活时间TimeUnit.SECONDS,//临时线程存活时间单位new ArrayBlockingQueue<>(4),//创建任务队列,最大存放任务数量为4Executors.defaultThreadFactory(),//线程工厂,//用到了Executors工具类来创建默认线程工厂new ThreadPoolExecutor.AbortPolicy());//拒绝策略,默认策略:抛出异常//定义出Runnable类型的任务MyRunnable myRunnable1 = new MyRunnable();MyRunnable myRunnable2 = new MyRunnable();MyRunnable myRunnable3 = new MyRunnable();MyRunnable myRunnable4 = new MyRunnable();MyRunnable myRunnable5 = new MyRunnable();//将该任务提交给线程池threadPool.execute(myRunnable1);threadPool.execute(myRunnable2);threadPool.execute(myRunnable3);threadPool.execute(myRunnable4);threadPool.execute(myRunnable5);//还没执行完的任务会交给l链表List<Runnable> l = ((ThreadPoolExecutor) threadPool).shutdownNow();for (int i = 0; i < l.size(); i++) {System.out.println("还没来得及执行的任务:" + l.get(i));}}
}
class  MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "正在执行");}
}

运行结果:

        3.4 临时线程什么时候创建?

        新任务提交时发现核心线程都在忙,任务队列也满了,并且还可以创建临时线程,此时才会创建临时线程。

代码如下:

import java.util.concurrent.*;
public class T {public static void main(String[] args) {Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量5,//最大线程数量8,//临时线程存活时间TimeUnit.SECONDS,//临时线程存活时间单位new ArrayBlockingQueue<>(4),//创建任务队列,最大存放任务数量为4Executors.defaultThreadFactory(),//线程工厂,//用到了Executors工具类来创建默认线程工厂new ThreadPoolExecutor.AbortPolicy());//拒绝策略,默认策略抛出异常//定义出Runnable类型的任务,此时该三个任务都被核心线程正在处理MyRunnable myRunnable1 = new MyRunnable();MyRunnable myRunnable2 = new MyRunnable();MyRunnable myRunnable3 = new MyRunnable();//这里还没到临时线程创建的时机,被放入到任务队列中等待被核心线程执行MyRunnable myRunnable4 = new MyRunnable();MyRunnable myRunnable5 = new MyRunnable();MyRunnable myRunnable6 = new MyRunnable();MyRunnable myRunnable7 = new MyRunnable();//此时到了临时线程创建的时机了,核心线程都在满,队列已经满了//创建出第一个临时线程MyRunnable myRunnable8 = new MyRunnable();//创建出第二个临时线程MyRunnable myRunnable9 = new MyRunnable();//将该任务提交给线程池threadPool.execute(myRunnable1);threadPool.execute(myRunnable2);threadPool.execute(myRunnable3);threadPool.execute(myRunnable4);threadPool.execute(myRunnable5);threadPool.execute(myRunnable6);threadPool.execute(myRunnable7);threadPool.execute(myRunnable8);threadPool.execute(myRunnable9);}
}class  MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "==> 正在执行" + this);try {//在这里等待10sThread.sleep(10000);} catch (InterruptedException e) {throw new RuntimeException(e);}}
}

运行结果:

        当前的核心线程为 3 ,最大线程为 5 且任务队列有四个位置。当核心线程达到 3 时,且任务队列满 4 个了,还能创建临时线程时提交新任务就可以创建出临时线程了。

        3.5 什么时候会开始拒绝新任务?

        核心线程和临时线程都在忙,任务队列也满了,新的任务过来的时候才会开始拒绝任务。

代码如下:

import java.util.concurrent.*;
public class T {public static void main(String[] args) {Executor threadPool = new ThreadPoolExecutor(3,//核心线程数量5,//最大线程数量8,//临时线程存活时间TimeUnit.SECONDS,//临时线程存活时间单位new ArrayBlockingQueue<>(4),//创建任务队列,最大存放任务数量为4Executors.defaultThreadFactory(),//线程工厂,//用到了Executors工具类来创建默认线程工厂new ThreadPoolExecutor.AbortPolicy());//拒绝策略,默认策略抛出异常//定义出Runnable类型的任务,此时该三个任务都被核心线程正在处理MyRunnable myRunnable1 = new MyRunnable();MyRunnable myRunnable2 = new MyRunnable();MyRunnable myRunnable3 = new MyRunnable();//这里还没到临时线程创建的时机,被放入到任务队列中等待被核心线程执行MyRunnable myRunnable4 = new MyRunnable();MyRunnable myRunnable5 = new MyRunnable();MyRunnable myRunnable6 = new MyRunnable();MyRunnable myRunnable7 = new MyRunnable();//此时到了临时线程创建的时机了,核心线程都在满,队列已经满了//创建出第一个临时线程MyRunnable myRunnable8 = new MyRunnable();//创建出第二个临时线程MyRunnable myRunnable9 = new MyRunnable();//此时核心线程都在忙,且队列已经占满了,再提交新任务的时候,//就会采取拒绝策略MyRunnable myRunnable10 = new MyRunnable();//将该任务提交给线程池threadPool.execute(myRunnable1);threadPool.execute(myRunnable2);threadPool.execute(myRunnable3);threadPool.execute(myRunnable4);threadPool.execute(myRunnable5);threadPool.execute(myRunnable6);threadPool.execute(myRunnable7);threadPool.execute(myRunnable8);threadPool.execute(myRunnable9);threadPool.execute(myRunnable10);}
}class  MyRunnable implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "==> 正在执行" + this);try {//在这里等待10sThread.sleep(10000);} catch (InterruptedException e) {throw new RuntimeException(e);}}
}

运行结果:

        拒绝策略默认是抛出异常

        4.0 线程池处理 Callable 任务

        处理Callable任务时,线程池可通过 submit() 方法提交 Callable 实例,并返回代表任务执行情况的 Future 。通过 Future 可以获取任务执行结果或处理异常

ExecutorService 常见的方法:

        4.1 通过 submit() 方法

        提交 Callable 类型的任务给线程池,线程池会选择可用线程、自动执行 call() 方法、自动启动线程。

代码如下:

import java.util.concurrent.*;public class MyCreateThreadPool {public static void main(String[] args) throws ExecutionException, InterruptedException {ExecutorService executor = new ThreadPoolExecutor(3,5,8,TimeUnit.SECONDS,new ArrayBlockingQueue<>(4),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());//创建出Callable类型的实例对象MyCallable callable1 = new MyCallable(100);MyCallable callable2 = new MyCallable(200);MyCallable callable3 = new MyCallable(300);MyCallable callable4 = new MyCallable(400);//将任务提交到线程池中Future<String> f1 = executor.submit(callable1);Future<String> f2 = executor.submit(callable2);Future<String> f3 = executor.submit(callable3);Future<String> f4 = executor.submit(callable4);//拿到结果System.out.println(f1.get());System.out.println(f2.get());System.out.println(f3.get());System.out.println(f4.get());}
}

运行结果:

        5.0 通过 Executors 工具类创建出线程池

        Executors 工具类提供了创建不同类型线程池的方法,如 newFixedThreadPool 、 newCachedThreadPool、newSingleThreadExecutor 等。这些方法返回不同配置的线程池实例,可用于执行 Runnable 和 Callable 任务。通过 Executors 创建线程池,可方便地管理线程池的大小、任务队列、线程工厂等参数。注意合理选择线程池类型以满足任务需求,避免资源浪费或任务阻塞。

        简单来说,Executors 工具类为我们提供了不同特点的线程池。

        5.1 通过 Executors.newFixedThreadPool(int nThreads) 方法来创建线程池

        创建固定线程数量的线程池,如果某个线程因执行异常而结束,那么线程池会补充一个新线程代替它。

代码如下:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class demo1 {public static void main(String[] args) {//固定的线程池核心线程为3,临时线程为0,所以最大线程数量也就是3。ExecutorService pool = Executors.newFixedThreadPool(3);pool.execute(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "==> 正在执行");}});pool.execute(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "==> 正在执行");}});pool.execute(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "==> 正在执行");}});pool.execute(new Runnable() {@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + "==> 正在执行");}});}
}

运行结果:

        其实 Executors.newFixedThreadPool(int nThreads) 方法的底层就是通过 ThreadPoolExecutor 类来实现创建线程池的。传入的参数就是核心线程线程数量,也为最大线程数量,因此临时线程数量为 0 。因此没有临时线程的存在,那么该线程池中的线程很固定

如图:

        5.2 通过 Executors.newCachedThreadPool() 方法来创建线程池

        线程数量随着任务增加而增加,如果线程任务执行完毕且空闲了 60 s则会被回收掉。也就是有多少了任务线程池会根据任务数量动态创建新线程。

代码如下:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;public class demo2 {public static void main(String[] args) {ExecutorService executorService = Executors.newCachedThreadPool();executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));System.out.println( ((ThreadPoolExecutor)executorService).getPoolSize());}
}

        通过 getPoolSize() 方法可以拿到当前线程池中线程的数量。

运行结果如下:

        该方法创建出来的线程池特点为,当任务越多时候,线程池中的线程数量也会随之增加。其实这个方法的底层实现也是通过 ThreadPoolExecutor 类来实现创建线程池。

如图:

        很惊奇的发现,核心线程竟然是 0 个,而临时线程数量的最大值是非常非常大的,如果线程任务执行完毕且空闲了 60 s则会被回收掉。

        5.3 通过 Eexcutors.newSingleThreadExecutor() 方法来创建线程池

        创建只有一个线程的线程池对象,如果该线程出现异常而结束,那么线程池会补充一个新线程。

代码如下:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class demo3 {public static void main(String[] args) {ExecutorService executorService = Executors.newSingleThreadExecutor();executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));executorService.execute(() -> System.out.println(Thread.currentThread().getName() + " ==> 正在执行"));}
}

运行结果:

        因为该线程池中只有一个线程,所以该线程需要执行所有的任务。因此该方法创建出来的线程池特点是,只有一个线程。当然该方法的底层也是通过 ThreadPoolExecutor 类来试下创建线程池。

如图:

        核心线程只有一个,最大线程也是一个,说明临时线程为零个。因此线程池中只有单一的线程。

        6.0 新任务拒绝策略

        常见的拒绝策略包括:AbortPolicy(默认策略,直接抛出异常)、CallerRunsPolicy(由调用线程执行任务)、DiscardPolicy(直接丢弃任务)、DiscardOldestPolicy(丢弃队列中最旧的任务)。

        6.1 AbortPolicy(默认策略,直接抛出异常)

        丢弃任务并抛出 RejectedExecutionExeception 异常,是默认的策略。

代码如下:

import java.util.concurrent.*;public class demo1 {public static void main(String[] args) {ExecutorService executorService = new ThreadPoolExecutor(2,3,8,TimeUnit.SECONDS,new ArrayBlockingQueue<>(2),Executors.defaultThreadFactory(),//默认拒绝新任务的策略new ThreadPoolExecutor.AbortPolicy());executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时会有临时线程创建executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时新任务提交的时候,会触发拒绝策略executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});}
}

运行结果:

        新提交的任务就被抛弃了且抛出异常。

        6.2 DiscardPolicy(直接丢弃任务)

        丢弃任务,但是不抛出异常,这是不推荐的做法。

代码如下:

import java.util.concurrent.*;public class demo1 {public static void main(String[] args) {ExecutorService executorService = new ThreadPoolExecutor(2,3,8,TimeUnit.SECONDS,new ArrayBlockingQueue<>(2),Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时会有临时线程创建executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时新任务提交的时候,会触发拒绝策略executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});}
}

运行结果:

        6.3 CallerRunsPolicy(由调用线程执行任务)

        由主线程负责调用任务的 run() 方法从而绕过线程池直接执行。

        简单来说,就是交给 main 主线程执行该任务。

代码如下:

import java.util.concurrent.*;public class demo1 {public static void main(String[] args) {ExecutorService executorService = new ThreadPoolExecutor(2,3,8,TimeUnit.SECONDS,new ArrayBlockingQueue<>(2),Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时会有临时线程创建executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时新任务提交的时候,会触发拒绝策略executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});}
}

        6.4 DiscardOldestPolicy(丢弃队列中最旧的任务)

        抛弃队列中等待最久的任务,然后把当前任务假如队列中。

import java.util.concurrent.*;public class demo1 {public static void main(String[] args) {ExecutorService executorService = new ThreadPoolExecutor(2,3,8,TimeUnit.SECONDS,new ArrayBlockingQueue<>(2),Executors.defaultThreadFactory(),//默认拒绝新任务的策略new ThreadPoolExecutor.DiscardOldestPolicy());executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时会有临时线程创建executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});//此时新任务提交的时候,会触发拒绝策略executorService.execute(() -> {System.out.println(Thread.currentThread().getName() + "正在执行");try {Thread.sleep(Integer.MAX_VALUE);} catch (InterruptedException e) {throw new RuntimeException(e);}});}
}

运行结果:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/597925.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于springboot+vue的地方美食分享网站(全套资料)

一、系统架构 前端&#xff1a;vue | element-ui 后端&#xff1a;springboot | mybatis-plus 环境&#xff1a;jdk8 | mysql | maven | node 二、代码及数据库 三、功能介绍 01. 用户端-登录 02. 用户端-首页 03. 用户端-外国美食 04. 用户端-中式美食 05. 用户端-热…

Centos7使用docker安装Jenkins(含pipeline脚本语句)

一、下载Jenkins docker pull jenkins/jenkins:lts 二、启动Jenkins docker run \-u root \--rm \-d \-p 8081:8080 \-p 50000:50000 \-v /root/docker/jenkins/var/jenkins_home:/var/jenkins_home \-v /var/run/docker.sock:/var/run/docker.sock \-v /usr/bin/docker:/usr…

2024.4.4-day09-CSS 布局模型(标准流模型、浮动模型)

个人主页&#xff1a;学习前端的小z 个人专栏&#xff1a;HTML5和CSS3悦读 本专栏旨在分享记录每日学习的前端知识和学习笔记的归纳总结&#xff0c;欢迎大家在评论区交流讨论&#xff01; 文章目录 作业 2024.4.4-学习笔记1 CSS 布局模型1.1 标准流1.2 CSS 浮动1.3 去除塌陷 2…

记Postman参数化

因为需要在WEB页面上处理部分数据&#xff0c;手动操作太慢&#xff0c;所以考虑使用接口方式处理&#xff0c;因急于使用&#xff0c;用Python Request的方式&#xff0c;写代码也来得慢&#xff0c;故采用Postman加外部文件参数化方式来实现。 接口请求是Post方式&#xff0c…

光伏接口转接器配合光伏规约转换器实现发电用电信息采集支持接入各个型号逆变器

1.产品概述 DAQ-GP-485PIA光伏接口转接器&#xff08;以下简称转接器&#xff09;是我公司针对光伏发电领域国家电网公司最新需求设计的&#xff0c;光伏接口转接器是配合光伏规约转换器&#xff0c;实现逆变器发电、用电信息采集的设备。支持锦浪、古瑞瓦特、固德威、华为、奥…

115.不同的子序列

给你两个字符串 s 和 t &#xff0c;统计并返回在 s 的 子序列 中 t 出现的个数&#xff0c;结果需要对 109 7 取模。 示例 1&#xff1a; 输入&#xff1a;s "rabbbit", t "rabbit" 输出&#xff1a;3 解释&#xff1a; 如下所示, 有 3 种可以从 s 中…

[AI in sec]-039 DNS隐蔽信道的检测-特征构建

DNS隐蔽信道是什么 DCC是指利用DNS数据包中的可定义字段秘密传递信息的通道。其中,“DNS 协议”是目前网络上使用的标准域名解析协议;“可定义字段”是DNS 数据包中的 QNAME 字段、RDATA 字段及RawUDP字段。利用DNS数据包可以构建2种信道:存储信道及时间信道。DCC可以被用于…

CTF之GET和POST

学过php都知道就一个简单传参&#xff0c;构造payload:?whatflag得到 flag{3121064b1e9e27280f9f709144222429} 下面是POST那题 使用firefox浏览器的插件Hackbar勾选POST传入whatflag flag{828a91acc006990d74b0cb0c2f62b8d8}

通过Omnet++官网tictoc教程学习在Omnet++中构建和运行仿真 Part1Part2

introduce开始模型介绍构建项目添加 NED 文件添加C 文件添加 omnetpp.ini总结 运行仿真启动仿真程序运行仿真调试运行时错误崩溃断点调试下一事件 调试/运行 日志序列图可视化 Omnet官网 TicToc教学 introduce 在 Omnet安装完成后&#xff0c;samples/tictoc 中有该例子的完整…

Unity Toggle组件

Toggle Group组件 Allow Switch Off属性值为false时&#xff0c; 1&#xff0c;Toggle初始时默认会有一个被勾选&#xff08;ison为true&#xff09;&#xff0c;可以自己打勾指定 2&#xff0c;不能取消勾选 Allow Switch Off属性值为true时&#xff0c; 1&#xff0c;Toggl…

第十四届蓝桥杯岛屿个数

题目描述&#xff1a; 小蓝得到了一副大小为 MN 的格子地图&#xff0c;可以将其视作一个只包含字符 0&#xff08;代表海水&#xff09;和 1&#xff08;代表陆地&#xff09;的二维数组&#xff0c;地图之外可以视作全部是海水&#xff0c;每个岛屿由在上/下/左/右四个方向上…