1. 首页 / 帮助

线程池的几个参数(线程池的几种方式)

线程池的几个参数,线程池的几种方式相信很多小伙伴还不知道,现在让我们一起来看看吧!

1、首先说明下java线程是如何实现线程重用的1. 线程执行完一个Runnable的run()方法后,不会被杀死 2. 当线程被重用时,这个线程会进入新Runnable对象的run()方法12java线程池由Executors提供的几种静态方法创建线程池。

2、下面通过代码片段简单介绍下线程池的几种实现方式。

3、后续会针对每个实现方式做详细的说明newFixedThreadPool创建一个固定大小的线程池 添加的任务达到线程池的容量之后开始加入任务队列开始线程重用总共开启线程个数跟指定容量相同。

[email protected] void newFixedThreadPool() throws Exception {ExecutorService executorService = Executors.newFixedThreadPool(1);executorService = Executors.newFixedThreadPool(1, new ThreadFactoryBuilder().build());RunThread run1 = new RunThread("run 1");executorService.execute(run1);executorService.shutdown();}12345678newSingleThreadExecutor仅支持单线程顺序处理任[email protected] void newSingleThreadExecutor() throws Exception {ExecutorService executorService = Executors.newSingleThreadExecutor();executorService = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().build());executorService.execute(new RunThread("run 1"));executorService.execute(new RunThread("run 2"));executorService.shutdown();}123456789newCachedThreadPool这种情况跟第一种的方式类似,不同的是这种情况线程池容量上线是Integer.MAX_VALUE [email protected] void newCachedThreadPool() throws Exception {ExecutorService executorService = Executors.newCachedThreadPool();executorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().build());executorService.execute(new RunThread("run 1"));executorService.execute(new RunThread("run 2"));executorService.shutdown();}123456789newWorkStealingPool支持给定的并行级别,并且可以使用多个队列来减少争用。

[email protected] void newWorkStealingPool() throws Exception {ExecutorService executorService = Executors.newWorkStealingPool();executorService = Executors.newWorkStealingPool(1);RunThread run1 = new RunThread("run 1");executorService.execute(run1);executorService.shutdown();}123456789newScheduledThreadPool看到的现象和第一种相同,也是在线程池满之前是新建线程,然后开始进入任务队列,进行线程重用 支持定时周期执行任务(还没有看完)@Testpublic void newScheduledThreadPool() throws Exception {ExecutorService executorService = Executors.newScheduledThreadPool(1);executorService = Executors.newScheduledThreadPool(1, new ThreadFactoryBuilder().build());executorService.execute(new RunThread("run 1"));executorService.execute(new RunThread("run 2"));executorService.shutdown();}。

本文就为大家分享到这里,希望小伙伴们会喜欢。

本文由'桂夜柔'发布,不代表演示站立场,转载/删除联系作者,如需删除请-> 关于侵权处理说明