当前位置: 首页 > news >正文

线程池的使用详解

一 使用线程池的好处

池化技术相比大家已经屡见不鲜了,线程池、数据库连接池、Http 连接池等等都是对这个思想的应用。池化技术的思想主要是为了减少每次获取资源的消耗,提高对资源的利用率。

 

线程池提供了一种限制和管理资源(包括执行一个任务)。 每个线程池还维护一些基本统计信息,例如已完成任务的数量。

这里借用《Java 并发编程的艺术》提到的来说一下使用线程池的好处

  • 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
  • 提高响应速度。当任务到达时,任务可以不需要的等到线程创建就能立即执行。
  • 提高线程的可管理性。线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。

二、线程池的核心参数

corePoolSize 线程池核心线程大小

maximumPoolSize 线程池最大线程数量

keepAliveTime 空闲线程存活时间

unit 空闲线程存活时间单位

workQueue 工作队列

threadFactory 线程工厂

handler 拒绝策略

 三、Runnable和ThreadPoolExecutor的使用

1.首先创建一个 Runnable 接口的实现类(当然也可以是 Callable 接口,我们上面也说了两者的区别。)MyRunnable.java

package com.newstart.controller;import java.util.Date;public class MyRunnable implements Runnable{private String command;public MyRunnable(String s) {this.command = s;}@Overridepublic void run() {System.out.println(Thread.currentThread().getName() + " Start. Time = " + new Date());processCommand();System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());}private void processCommand() {try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}}@Overridepublic String toString() {return this.command;}
}

2.编写测试程序,我们这里以阿里巴巴推荐的使用 ThreadPoolExecutor 构造函数自定义参数的方式来创建线程池。ThreadPoolExecutorDemo.java

package com.newstart.controller;import java.util.concurrent.*;public class ThreadPoolExecutorDemo {private static final int CORE_POOL_SIZE = 5;private static final int MAX_POOL_SIZE = 10;private static final int QUEUE_CAPACITY = 100;private static final Long KEEP_ALIVE_TIME = 1L;public static void main(String[] args) throws InterruptedException {//使用阿里巴巴推荐的创建线程池的方式//通过ThreadPoolExecutor构造函数自定义参数创建ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME,TimeUnit.SECONDS,new ArrayBlockingQueue<>(QUEUE_CAPACITY),new ThreadPoolExecutor.CallerRunsPolicy());for (int i=0;i<10;i++){//创建WorkerThread对象(WorkerThread类实现了Runnable 接口)Runnable worker = new MyRunnable("" + i);//执行Runnableexecutor.execute(worker);}//终止线程池executor.shutdown();while (!executor.isTerminated()) {}System.out.println("Finished all threads");}
}

四、使用Callable和和ThreadPoolExecutor的使用

1.首先创建一个 Callable 接口的实现类MyCallable.java

package com.newstart.controller;import java.util.Date;
import java.util.concurrent.Callable;public class MyCallble implements Callable {private String command;public MyCallble(String s) {this.command = s;}private void processCommand() {try {Thread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}}@Overridepublic String toString() {return this.command;}@Overridepublic Object call() throws Exception {System.out.println(Thread.currentThread().getName() + " Start. Time = " + new Date());processCommand();System.out.println(Thread.currentThread().getName() + " End. Time = " + new Date());return Thread.currentThread().getName();}
}

2.编写测试程序,我们这里以阿里巴巴推荐的使用 ThreadPoolExecutor 构造函数自定义参数的方式来创建线程池。ThreadPoolExecutorDemo.java

package com.newstart.controller;import java.util.concurrent.*;public class ThreadPoolExecutorDemo {private static final int CORE_POOL_SIZE = 5;private static final int MAX_POOL_SIZE = 10;private static final int QUEUE_CAPACITY = 100;private static final Long KEEP_ALIVE_TIME = 1L;public static void main(String[] args) throws InterruptedException {//使用阿里巴巴推荐的创建线程池的方式//通过ThreadPoolExecutor构造函数自定义参数创建ThreadPoolExecutor executor = new ThreadPoolExecutor(CORE_POOL_SIZE,MAX_POOL_SIZE,KEEP_ALIVE_TIME,TimeUnit.SECONDS,new ArrayBlockingQueue<>(QUEUE_CAPACITY),new ThreadPoolExecutor.CallerRunsPolicy());for (int i=0;i<10;i++){//创建WorkerThread对象(WorkerThread类实现了Runnable 接口)Callable worker = new MyCallble("" + i);//执行RunnableFuture future = executor.submit(worker);Thread.sleep(1000);System.out.println(future.isDone());}//终止线程池executor.shutdown();while (!executor.isTerminated()) {}System.out.println("Finished all threads");}
}

Callable和Runnable的区别:

Runnable无返回值

Callable有返回值,并且可以抛出异常

在线程池中:

对于Callable接口需要使用submit执行,并且返回值为future,通过future的isdone方法可以判断线程是否执行完毕

对于Runnable接口需要使用execute执行

 shutdown()和 shutdownNow()的区别

  • shutdown() :关闭线程池,线程池的状态变为 SHUTDOWN。线程池不再接受新任务了,但是队列里的任务得执行完毕。
  • shutdownNow() :关闭线程池,线程的状态变为 STOP。线程池会终止当前正在运行的任务,并停止处理排队的任务并返回正在等待执行的 List。

 

http://www.lryc.cn/news/104802.html

相关文章:

  • 刷题笔记 day4
  • Python 2.x 中如何使用flask模块进行Web开发
  • spring websocket 调用受权限保护的方法失败
  • Vue.js2+Cesium 四、模型对比
  • Linux 之 Vi 编辑器
  • Python超实用!批量重命名文件/文件夹,只需1行代码
  • sqoop
  • PySpark 数据操作(综合案例)
  • 产品经理如何平衡用户体验与商业价值?
  • 【PostgreSQL】系列之 一 CentOS 7安装PGSQL15版本(一)
  • Nginx解决文件服务器文件名显示不全的问题
  • IO进程线程第四天(8.1)
  • WAF绕过-权限控制篇-后门免杀
  • LED灯的驱动,GPIO子系统,添加按键的中断处理
  • Gradle和Maven的区别
  • C#中 使用yield return 优化大数组或集合的访问
  • ROS实现导航中止(pub命令版+C++代码版)
  • 【VTK】读取一个 STL 文件,并使用 Qt 显示出来,在 Windows 上使用 Visual Studio 配合 Qt 构建 VTK
  • 数据结构--基础知识
  • 天工开物 #7 Rust 与 Java 程序的异步接口互操作
  • python实现视频转GIF动图(无水印,包含代码详解和.exe执行文件)
  • 一套AI+医疗模式的医院智慧导诊系统源码:springboot+redis+mybatis plus+mysql
  • Android 使用modbus协议与可能遇到的问题解决一览
  • Virtualbox虚拟机中Ubuntu忘记密码
  • isPresent()
  • DC.js教程_编程入门自学教程_菜鸟教程-免费教程分享
  • Qt应用开发(基础篇)——滑块类 Slider、ScrollBar、Dial
  • iOS的NSUserActivity
  • Android HTTP使用(详细版)
  • 【雕爷学编程】MicroPython动手做(25)——语音合成与语音识别