博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程之线程池
阅读量:3947 次
发布时间:2019-05-24

本文共 1223 字,大约阅读时间需要 4 分钟。

线程池

  1. 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
  2. 思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池子中。可以避免频繁的资源消耗,实现了重复利用。
  3. 好处:提高响应速度(减少了创建新线程的时间),降低了资源消耗(重复利用线程池中的线程,不需要每次都创建),便于线程管理(例如常可以对其设置池子的大小,最大线程数,没有任务时线程保持多久会自动终止等等。)

使用线程池

  1. JDK5.0 起提供了线程池相关的API:ExecutorService 和 Executors
  2. ExecutorService :真正的线程池接口。常见字类 ThreadPoolExecutor
    void execute(Runnable command) 执行任务/命令,没有返回值,一般用来执行 Runnable
    <T> Future<T> submit(Callable<T> task) 执行任务,有返回值,一般用来执行 Callable
    void shutdown() 关闭连接池
  3. ExecutorService :工具类,线程池的工厂类,用于创建并返回不同类型的线程池。

下面通过代码来实现一个小案例:

package org.javaboy.juc;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @Author: bai * @DateTime: 2020/6/7 21:51 */public class TestPool {
public static void main(String[] args) {
// step1.创建服务,创建线程池 // newFixedThreadPool 参数为:线程池大小 ExecutorService service = Executors.newFixedThreadPool(10); // step2.执行 service.execute(new MyThread()); service.execute(new MyThread()); service.execute(new MyThread()); // step3.关闭连接 service.shutdown(); }}class MyThread implements Runnable {
@Override public void run() {
System.out.println(Thread.currentThread().getName()); }}

转载地址:http://xvqwi.baihongyu.com/

你可能感兴趣的文章
Naive Bayesian for Text Classification (MLE, Gaussian Naive Bayesian)
查看>>
Algorithm: Decision Tree, Entropy, Information Gain and Continues features
查看>>
FastDFS 架构分析
查看>>
Windows 应用生成MiniDump文件的方法笔记
查看>>
安装FastDFS单机版环境
查看>>
动态规划-背包问题
查看>>
Windows10 + Nodejs调用C++语言Dll
查看>>
CSAPP - 一个简单的Shell
查看>>
《算法4》 Windows/Mac环境下使用Visual Studio Code和Orcale JDK1.8开发环境搭建
查看>>
精心整理很实用的前端笔记,看完你就在css上有很深的造诣了!!!
查看>>
前端开发在工作中用到的工具、软件、库.......------Sesiid
查看>>
正则表达式~~~很全的------Sestid
查看>>
在HTML中嵌入百度地图------Sestid
查看>>
Js或jQuery图片层叠轮播------Sestid
查看>>
js或jQuery实现返回顶部功能------Sestid
查看>>
JS实现拖拽效果------Sestid
查看>>
jQuery实现倒计时秒杀效果------Sestid
查看>>
jQuery实现html网页顶部自适应导航栏(media)------Sestid
查看>>
鼠标悬停显示下划线(带小特效)------Sestid
查看>>
jQuery 实现input搜索框自动匹配------Sestid
查看>>