http://heipark.iteye.com/blog/1393847

Executors.newFixedThreadPool和ArrayBlockingQueue一点使用心得      

    博客分类:

  • Java
 

newFixedThreadPool使用范例:

  1. import java.io.IOException;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. public class Test {
  5. public static void main(String[] args) throws IOException, InterruptedException {
  6. ExecutorService service = Executors.newFixedThreadPool(2);
  7. for (int i = 0; i < 6; i++) {
  8. final int index = i;
  9. System.out.println("task: " + (i+1));
  10. Runnable run = new Runnable() {
  11. @Override
  12. public void run() {
  13. System.out.println("thread start" + index);
  14. try {
  15. Thread.sleep(Long.MAX_VALUE);
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. System.out.println("thread end" + index);
  20. }
  21. };
  22. service.execute(run);
  23. }
  24. }
  25. }
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class Test { public static void main(String[] args) throws IOException, InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(2);
for (int i = 0; i < 6; i++) {
final int index = i;
System.out.println("task: " + (i+1));
Runnable run = new Runnable() {
@Override
public void run() {
System.out.println("thread start" + index);
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread end" + index);
}
};
service.execute(run);
}
}
}
 输出:
task: 1

task: 2

thread start0

task: 3

task: 4

task: 5

task: 6

task: 7

thread start1

task: 8

task: 9

task: 10

task: 11

task: 12

task: 13

task: 14

task: 15

从实例可以看到for循环并没有被固定的线程池阻塞住,也就是说所有的线程task都被提交到了ExecutorService中,查看 Executors.newFixedThreadPool()如下:

public static ExecutorService newFixedThreadPool(int nThreads) {

        return new ThreadPoolExecutor(nThreads, nThreads,

                                      0L, TimeUnit.MILLISECONDS,

                                      new LinkedBlockingQueue<Runnable>());

    }

可以看到task被提交都了LinkedBlockingQueue中。这里有个问题,如果任务列表很大,一定会把内存撑爆,如何解决?看下面:

  1. import java.io.IOException;
  2. import java.util.concurrent.ArrayBlockingQueue;
  3. import java.util.concurrent.BlockingQueue;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. import java.util.concurrent.TimeUnit;
  6. public class Test {
  7. public static void main(String[] args) throws IOException, InterruptedException {
  8. BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(3);
  9. ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1, TimeUnit.HOURS, queue, new ThreadPoolExecutor.CallerRunsPolicy());
  10. for (int i = 0; i < 10; i++) {
  11. final int index = i;
  12. System.out.println("task: " + (index+1));
  13. Runnable run = new Runnable() {
  14. @Override
  15. public void run() {
  16. System.out.println("thread start" + (index+1));
  17. try {
  18. Thread.sleep(Long.MAX_VALUE);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. System.out.println("thread end" + (index+1));
  23. }
  24. };
  25. executor.execute(run);
  26. }
  27. }
  28. }
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; public class Test { public static void main(String[] args) throws IOException, InterruptedException { BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(3); ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 3, 1, TimeUnit.HOURS, queue, new ThreadPoolExecutor.CallerRunsPolicy()); for (int i = 0; i < 10; i++) {
final int index = i;
System.out.println("task: " + (index+1));
Runnable run = new Runnable() {
@Override
public void run() {
System.out.println("thread start" + (index+1));
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread end" + (index+1));
}
};
executor.execute(run);
}
}
}
 输出:
task: 1

task: 2

thread start1

task: 3

task: 4

task: 5

task: 6

task: 7

thread start2

thread start7

thread start6

线程池最大值为4(??这里我不明白为什么是设置值+1,即3+1,而不是3),准备执行的任务队列为3。可以看到for循环先处理4个task,然后把3个放到队列。这样就实现了自动阻塞队列的效果。记得要使用ArrayBlockingQueue这个队列,然后设置容量就OK了。

--heipark

ExecutorService,另一种服务,线程的更多相关文章

  1. java线程池与五种常用线程池策略使用与解析

    背景:面试中会要求对5中线程池作分析.所以要熟知线程池的运行细节,如CachedThreadPool会引发oom吗? java线程池与五种常用线程池策略使用与解析 可选择的阻塞队列BlockingQu ...

  2. 四种Java线程池用法解析

    本文为大家分析四种Java线程池用法,供大家参考,具体内容如下 http://www.jb51.net/article/81843.htm 1.new Thread的弊端 执行一个异步任务你还只是如下 ...

  3. Java开发笔记(一百零五)几种定时器线程池

    前面介绍了普通线程池的用法,就大多数任务而言,它们对具体的执行时机并无特殊要求,最多是希望早点跑完早点出结果.不过对于需要定时执行的任务来说,它们要求在特定的时间点运行,并且往往不止运行一次,还要周期 ...

  4. java线程池和五种常用线程池的策略使用与解析

    java线程池和五种常用线程池策略使用与解析 一.线程池 关于为什么要使用线程池久不赘述了,首先看一下java中作为线程池Executor底层实现类的ThredPoolExecutor的构造函数 pu ...

  5. 解决了一个java服务线程退出的问题

    问题背景 ​ 早上才上班,测试就提了一个问题:"昨天所有批量任务都没有跑".我看了一下任务监控页面,任务是有生成的,但却一直在等待调度状态.初步怀疑是我们的调度服务问题,于是上去查 ...

  6. 云计算的三种服务模式:SaaS/PaaS/IaaS

    转载http://blog.chinaunix.net/uid-22414998-id-3141499.html 定义 云计算主要分为三种服务模式,而且这个三层的分法重要是从用户体验的角度出发的: S ...

  7. 云计算三种服务模式SaaS、PaaS和IaaS及其之间关系(顺带CaaS、MaaS)

    云计算架构图 很明显,这五者之间主要的区别在于第一个单词,而aaS都是as-a-service(即服务)的意思,这五个模式都是近年来兴起的,且这五者都是云计算的落地产品,所以我们先来了解一下云计算是什 ...

  8. 浅淡Webservice、WSDL三种服务访问的方式(附案例)

    Webservice Webservice是使应用程序以与平台和编程语言无关的方式进行相互通信技术. eg:站点提供访问的数据接口:新浪微博.淘宝. 官方解释:它是一种构建应用程序的普遍模型,可以在任 ...

  9. ExecutorService 建立一个多线程的线程池的步骤

    ExecutorService 建立一个多线程的线程池的步骤: 线程池的作用: 线程池功能是限制在系统中运行的线程数. 依据系统的环境情况,能够自己主动或手动设置线程数量.达到执行的最佳效果:少了浪费 ...

随机推荐

  1. MySQL入门笔记(二)

    MySQL的数据类型.数据库操作.针对单表的操作以及简单的记录操作可参考:MySQL入门笔记(一) 五.子查询   子查询可简单地理解为查询中的查询,即子查询外部必然还有一层查询,并且这里的查询并非仅 ...

  2. 消息中间件kafka+zookeeper集群部署、测试与应用

    业务系统中,通常会遇到这些场景:A系统向B系统主动推送一个处理请求:A系统向B系统发送一个业务处理请求,因为某些原因(断电.宕机..),B业务系统挂机了,A系统发起的请求处理失败:前端应用并发量过大, ...

  3. 又把JDK改回JDK1.8的过程

    我已经在崩溃的边缘. 先在控制面板卸载9.0.4,非常好,卸的干干净净的. 然后继续卸载9.0.1,也很好,卸的很干净. 命令行: 安装JDK1.8 装完了,去配环境变量: 4个环境变量都配齐了. J ...

  4. hive数据库的哪些函数操作是否走MR

    平时我们用的HIVE 我们都知道 select * from table_name 不走MR 直接走HTTP hive 0.10.0为了执行效率考虑,简单的查询,就是只是select,不带count, ...

  5. sql性能优化之多表联查

    先贴上我优化后的核心代码: select * into #result from ( select p.AchivementCount,isnull(a.ByAttentionCount,0) ByA ...

  6. .net framework 4.5 +steeltoe+ springcloud 实现服务注册功能

    首先得先了解并熟悉一下springcloud,并手动去搭建一个服务中心,具体可度娘教程. 如果是.net core的话,实现注册也是没有问题的,网上教程很多,可自行度娘. 最难的就是基于Framewo ...

  7. 31.Django缓存和信号

    缓存 由于Django是动态网站,所有每次请求均会去数据进行相应的操作,当程序访问量大时,耗时必然会更加明显,最简单解决方式是使用:缓存,缓存将某个views的返回值保存至内存或者memcache中, ...

  8. Java基础知识回顾之一 ----- 基本数据类型

    前言 在开始工作至今,学习各种各样的技术之中发现自己的很多Java的基础知识都忘了⊙﹏⊙b汗... 而且越是学习越是发现Java基础的重要性,所以准备单独抽一下时间进行Java基础的重新学习.在重新学 ...

  9. 关于js高度和宽度的获取 ----2017-03-29

    来源:百度  对错有待实践检验 网页可见区域宽: document.body.clientWidth 网页可见区域高: document.body.clientHeight 网页可见区域宽: docu ...

  10. IE 兼容 getElementsByClassName

    getElementsByClassName 通过class获取节点,是很多新人练习原生JS都用到的,项目中也会写,当项目进行到一定程度时,测试IE低版本,忽然发现不支持的时候,瞬间感觉整个人都不好了 ...