热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

Java线程池的几种实现方法和区别介绍

下面小编就为大家带来一篇Java线程池的几种实现方法和区别。小编觉得挺不错的,现在分享给大家,也给大家做个参考,一起跟随小编过来看看吧,祝大家游戏愉快哦

Java线程池的几种实现方法和区别介绍

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestThreadPool {
 // -newFixedThreadPool与cacheThreadPool差不多,也是能reuse就用,但不能随时建新的线程
 // -其独特之处:任意时间点,最多只能有固定数目的活动线程存在,此时如果有新的线程要建立,只能放在另外的队列中等待,直到当前的线程中某个线程终止直接被移出池子
 // -和cacheThreadPool不同,FixedThreadPool没有IDLE机制(可能也有,但既然文档没提,肯定非常长,类似依赖上层的TCP或UDP
 // IDLE机制之类的),所以FixedThreadPool多数针对一些很稳定很固定的正规并发线程,多用于服务器
 // -从方法的源代码看,cache池和fixed 池调用的是同一个底层池,只不过参数不同:
 // fixed池线程数固定,并且是0秒IDLE(无IDLE)
 // cache池线程数支持0-Integer.MAX_VALUE(显然完全没考虑主机的资源承受能力),60秒IDLE
 private static ExecutorService fixedService = Executors.newFixedThreadPool(6);
 // -缓存型池子,先查看池中有没有以前建立的线程,如果有,就reuse.如果没有,就建一个新的线程加入池中
 // -缓存型池子通常用于执行一些生存期很短的异步型任务
 // 因此在一些面向连接的daemon型SERVER中用得不多。
 // -能reuse的线程,必须是timeout IDLE内的池中线程,缺省timeout是60s,超过这个IDLE时长,线程实例将被终止及移出池。
 // 注意,放入CachedThreadPool的线程不必担心其结束,超过TIMEOUT不活动,其会自动被终止。
 private static ExecutorService cacheService = Executors.newCachedThreadPool();
 // -单例线程,任意时间池中只能有一个线程
 // -用的是和cache池和fixed池相同的底层池,但线程数目是1-1,0秒IDLE(无IDLE)
 private static ExecutorService singleService = Executors.newSingleThreadExecutor();
 // -调度型线程池
 // -这个池子里的线程可以按schedule依次delay执行,或周期执行
 private static ExecutorService scheduledService = Executors.newScheduledThreadPool(10);

 public static void main(String[] args) {
  DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  List customerList = new ArrayList();
  System.out.println(format.format(new Date()));
  testFixedThreadPool(fixedService, customerList);
  System.out.println("--------------------------");
  testFixedThreadPool(fixedService, customerList);
  fixedService.shutdown();
  System.out.println(fixedService.isShutdown());
  System.out.println("----------------------------------------------------");
  testCacheThreadPool(cacheService, customerList);
  System.out.println("----------------------------------------------------");
  testCacheThreadPool(cacheService, customerList);
  cacheService.shutdownNow();
  System.out.println("----------------------------------------------------");
  testSingleServiceThreadPool(singleService, customerList);
  testSingleServiceThreadPool(singleService, customerList);
  singleService.shutdown();
  System.out.println("----------------------------------------------------");
  testScheduledServiceThreadPool(scheduledService, customerList);
  testScheduledServiceThreadPool(scheduledService, customerList);
  scheduledService.shutdown();
 }

 public static void testScheduledServiceThreadPool(ExecutorService service, List customerList) {
  List> listCallable = new ArrayList>();
  for (int i = 0; i <10; i++) {
   Callable callable = new Callable() {
    @Override
    public Integer call() throws Exception {
     return new Random().nextInt(10);
    }
   };
   listCallable.add(callable);
  }
  try {
   List> listFuture = service.invokeAll(listCallable);
   for (Future future : listFuture) {
    Integer id = future.get();
    customerList.add(id);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println(customerList.toString());
 }

 public static void testSingleServiceThreadPool(ExecutorService service, List customerList) {
  List>> listCallable = new ArrayList>>();
  for (int i = 0; i <10; i++) {
   Callable> callable = new Callable>() {
    @Override
    public List call() throws Exception {
     List list = getList(new Random().nextInt(10));
     boolean isStop = false;
     while (list.size() > 0 && !isStop) {
      System.out.println(Thread.currentThread().getId() + " -- sleep:1000");
      isStop = true;
     }
     return list;
    }
   };
   listCallable.add(callable);
  }
  try {
   List>> listFuture = service.invokeAll(listCallable);
   for (Future> future : listFuture) {
    List list = future.get();
    customerList.addAll(list);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println(customerList.toString());
 }

 public static void testCacheThreadPool(ExecutorService service, List customerList) {
  List>> listCallable = new ArrayList>>();
  for (int i = 0; i <10; i++) {
   Callable> callable = new Callable>() {
    @Override
    public List call() throws Exception {
     List list = getList(new Random().nextInt(10));
     boolean isStop = false;
     while (list.size() > 0 && !isStop) {
      System.out.println(Thread.currentThread().getId() + " -- sleep:1000");
      isStop = true;
     }
     return list;
    }
   };
   listCallable.add(callable);
  }
  try {
   List>> listFuture = service.invokeAll(listCallable);
   for (Future> future : listFuture) {
    List list = future.get();
    customerList.addAll(list);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println(customerList.toString());
 }

 public static void testFixedThreadPool(ExecutorService service, List customerList) {
  List>> listCallable = new ArrayList>>();
  for (int i = 0; i <10; i++) {
   Callable> callable = new Callable>() {
    @Override
    public List call() throws Exception {
     List list = getList(new Random().nextInt(10));
     boolean isStop = false;
     while (list.size() > 0 && !isStop) {
      System.out.println(Thread.currentThread().getId() + " -- sleep:1000");
      isStop = true;
     }
     return list;
    }
   };
   listCallable.add(callable);
  }
  try {
   List>> listFuture = service.invokeAll(listCallable);
   for (Future> future : listFuture) {
    List list = future.get();
    customerList.addAll(list);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  System.out.println(customerList.toString());
 }

 public static List getList(int x) {
  List list = new ArrayList();
  list.add(x);
  list.add(x * x);
  return list;
 }
}

使用:LinkedBlockingQueue实现线程池讲解

//例如:corePoolSize=3,maximumPoolSize=6,LinkedBlockingQueue(10)

//RejectedExecutionHandler默认处理方式是:ThreadPoolExecutor.AbortPolicy

//ThreadPoolExecutor executorService = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue(10));

//1.如果线程池中(也就是调用executorService.execute)运行的线程未达到LinkedBlockingQueue.init(10)的话,当前执行的线程数是:corePoolSize(3) 

//2.如果超过了LinkedBlockingQueue.init(10)并且超过的数>=init(10)+corePoolSize(3)的话,并且小于init(10)+maximumPoolSize. 当前启动的线程数是:(当前线程数-init(10))

//3.如果调用的线程数超过了init(10)+maximumPoolSize 则根据RejectedExecutionHandler的规则处理。

关于:RejectedExecutionHandler几种默认实现讲解

//默认使用:ThreadPoolExecutor.AbortPolicy,处理程序遭到拒绝将抛出运行时RejectedExecutionException。
			RejectedExecutionHandler policy=new ThreadPoolExecutor.AbortPolicy();
//			//在 ThreadPoolExecutor.CallerRunsPolicy 中,线程调用运行该任务的execute本身。此策略提供简单的反馈控制机制,能够减缓新任务的提交速度。
//			policy=new ThreadPoolExecutor.CallerRunsPolicy();
//			//在 ThreadPoolExecutor.DiscardPolicy 中,不能执行的任务将被删除。
//			policy=new ThreadPoolExecutor.DiscardPolicy();
//			//在 ThreadPoolExecutor.DiscardOldestPolicy 中,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)。
//			policy=new ThreadPoolExecutor.DiscardOldestPolicy();

以上这篇Java线程池的几种实现方法和区别介绍就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


推荐阅读
  • 本文介绍如何在现有网络中部署基于Linux系统的透明防火墙(网桥模式),以实现灵活的时间段控制、流量限制等功能。通过详细的步骤和配置说明,确保内部网络的安全性和稳定性。 ... [详细]
  • 本文将详细探讨 Linux 系统中的 netstat 命令,该命令用于查看网络状态和连接情况。通过了解 IP 地址和端口的基本概念,我们将更好地理解如何利用 netstat 命令来监控和管理网络服务。 ... [详细]
  • MQTT技术周报:硬件连接与协议解析
    本周开发笔记重点介绍了在新项目中使用MQTT协议进行硬件连接的技术细节,涵盖其特性、原理及实现步骤。 ... [详细]
  • UNP 第9章:主机名与地址转换
    本章探讨了用于在主机名和数值地址之间进行转换的函数,如gethostbyname和gethostbyaddr。此外,还介绍了getservbyname和getservbyport函数,用于在服务器名和端口号之间进行转换。 ... [详细]
  • 掌握远程执行Linux脚本和命令的技巧
    本文将详细介绍如何利用Python的Paramiko库实现远程执行Linux脚本和命令,帮助读者快速掌握这一实用技能。通过具体的示例和详尽的解释,让初学者也能轻松上手。 ... [详细]
  • 网络运维工程师负责确保企业IT基础设施的稳定运行,保障业务连续性和数据安全。他们需要具备多种技能,包括搭建和维护网络环境、监控系统性能、处理突发事件等。本文将探讨网络运维工程师的职业前景及其平均薪酬水平。 ... [详细]
  • 从零开始构建完整手机站:Vue CLI 3 实战指南(第一部分)
    本系列教程将引导您使用 Vue CLI 3 构建一个功能齐全的移动应用。我们将深入探讨项目中涉及的每一个知识点,并确保这些内容与实际工作中的需求紧密结合。 ... [详细]
  • 本文介绍如何通过SSH协议使用Xshell远程连接到Ubuntu系统。为了实现这一目标,需要确保Ubuntu系统已安装并配置好SSH服务器,并保证网络连通性。 ... [详细]
  • 深入解析 Spring Security 用户认证机制
    本文将详细介绍 Spring Security 中用户登录认证的核心流程,重点分析 AbstractAuthenticationProcessingFilter 和 AuthenticationManager 的工作原理。通过理解这些组件的实现,读者可以更好地掌握 Spring Security 的认证机制。 ... [详细]
  • 优化局域网SSH连接延迟问题的解决方案
    本文介绍了解决局域网内SSH连接到服务器时出现长时间等待问题的方法。通过调整配置和优化网络设置,可以显著缩短SSH连接的时间。 ... [详细]
  • Git管理工具SourceTree安装与使用指南
    本文详细介绍了Git管理工具SourceTree的安装、配置及团队协作方案,旨在帮助开发者更高效地进行版本控制和项目管理。 ... [详细]
  • 本文介绍如何配置SecureCRT以正确显示Linux终端的颜色,并解决中文显示问题。通过简单的步骤设置,可以显著提升使用体验。 ... [详细]
  • 本指南详细介绍了如何在同一台计算机上配置多个GitHub账户,并使用不同的SSH密钥进行身份验证,确保每个账户的安全性和独立性。 ... [详细]
  • 在Linux系统上构建Web服务器的详细步骤
    本文详细介绍了如何在Linux系统上搭建Web服务器的过程,包括安装Apache、PHP和MySQL等关键组件,以及遇到的一些常见问题及其解决方案。 ... [详细]
  • TCP/IP基础知识详解
    本文详细介绍了TCP/IP协议的基本概念,包括网络层次模型、TCP三次握手过程、四次挥手过程以及TCP与UDP的比较。通过这些内容,读者可以更好地理解TCP/IP协议的工作原理。 ... [详细]
author-avatar
多米音乐_34249295
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有