Executors

线程池ThreadPoolExecutor详解

醉酒当歌 提交于 2020-03-24 07:21:22
3 月,跳不动了?>>> 一简介 线程的使用在java中占有极其重要的地位,在jdk1.4极其之前的jdk版本中,关于线程池的使用是极其简陋的。在jdk1.5之后这一情况有了很大的改观。Jdk1.5之后加入了java.util.concurrent包,这个包中主要介绍java中线程以及线程池的使用。为我们在开发中处理线程的问题提供了非常大的帮助。 二:线程池 线程池的作用: 线程池作用就是限制系统中执行线程的数量。 根据系统的环境情况,可以自动或手动设置线程数量,达到运行的最佳效果;少了浪费了系统资源,多了造成系统拥挤效率不高。用线程池控制线程数量,其他线程排队等候。一个任务执行完毕,再从队列的中取最前面的任务开始执行。若队列中没有等待进程,线程池的这一资源处于等待。当一个新任务需要运行时,如果线程池中有等待的工作线程,就可以开始运行了;否则进入等待队列。 为什么要用线程池: 1.减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。 2.可以根据系统的承受能力,调整线程池中工作线线程的数目,防止因为消耗过多的内存,而把服务器累趴下(每个线程需要大约1MB内存,线程开的越多,消耗的内存也就越大,最后死机)。 Java里面线程池的顶级接口是Executor,但是严格意义上讲Executor并不是一个线程池,而只是一个执行线程的工具

java并发库之Executors常用的创建ExecutorService的几个方法说明

孤人 提交于 2020-02-29 20:00:36
一、线程池的创建 我们可以通过ThreadPoolExecutor来创建一个线程池。 new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, milliseconds,runnableTaskQueue, handler); 创建一个线程池需要输入几个参数: corePoolSize(线程池的基本大小):当提交一个任务到线程池时,线程池会创建一个线程来执行任务,即使其他空闲的基本线程能够执行新任务也会创建线程,等到需要执行的任务数大于线程池基本大小时就不再创建。如果调用了线程池的prestartAllCoreThreads方法,线程池会提前创建并启动所有基本线程。 runnableTaskQueue(任务队列):用于保存等待执行的任务的阻塞队列。 可以选择以下几个阻塞队列。 ArrayBlockingQueue:是一个基于数组结构的有界阻塞队列,此队列按 FIFO(先进先出)原则对元素进行排序。 LinkedBlockingQueue:一个基于链表结构的阻塞队列,此队列按FIFO (先进先出) 排序元素,吞吐量通常要高于ArrayBlockingQueue。静态工厂方法Executors.newFixedThreadPool()使用了这个队列。 SynchronousQueue

CompletionService 简介

情到浓时终转凉″ 提交于 2020-02-29 06:21:29
当向Executor提交批处理任务时,并且希望在它们完成后获得结果,如果用FutureTask,你可以循环获取task,并用future.get()去获取结果,但是如果这个task没有完成,你就得阻塞在这里,这个实效性不高,其实在很多场合,其实你拿第一个任务结果时,此时结果并没有生成并阻塞,其实在阻塞在第一个任务时,第二个task的任务已经早就完成了,显然这种情况用future task不合适的,效率也不高。 自己维护list和CompletionService的区别: 从list中遍历的每个Future对象并不一定处于完成状态,这时调用get()方法就会被阻塞住,如果系统是设计成每个线程完成后就能根据其结果继续做后面的事,这样对于处于list后面的但是先完成的线程就会增加了额外的等待时间。 而CompletionService的实现是维护一个保存Future对象的BlockingQueue。只有当这个Future对象状态是结束的时候,才会加入到这个Queue中,take()方法其实就是Producer-Consumer中的Consumer。它会从Queue中取出Future对象,如果Queue是空的,就会阻塞在那里,直到有完成的Future对象加入到Queue中。 CompletionService采取的是BlockingQueue<Future<V>>无界队列来管理Future

Java Executor with throttling/throughput control

谁都会走 提交于 2019-12-29 03:08:20
问题 I'm looking for a Java Executor that allows me to specify throttling/throughput/pacing limitations, for example, no more than say 100 tasks can be processed in a second -- if more tasks get submitted they should get queued and executed later. The main purpose of this is to avoid running into limits when hitting foreign APIs or servers. I'm wondering whether either base Java (which I doubt, because I checked) or somewhere else reliable (e.g. Apache Commons) provides this, or if I have to write

ThreadPool / Executor on both Runnable and Callable - that can exits automatically java8

拈花ヽ惹草 提交于 2019-12-24 02:09:34
问题 I am trying to use a ThreadPoolExecutor/ExecutorService in my application - it is a static global object. I use: Executors.newScheduledThreadPool(corePoolSize) - but I am having problems with shutting down the executorService. If I don't call shutdown() + awaitTermination() - then my application won't finish -even if all threads are completed. My application has threads being created by other threads - so I can't put a shutdown() anywhere in the code without blocking further threads to be run

ScheduledExecutorService, how to stop action without stopping executor?

心已入冬 提交于 2019-12-17 20:17:54
问题 I have this code: ScheduledExecutorService scheduledExecutor; ..... ScheduledFuture<?> result = scheduledExecutor.scheduleWithFixedDelay( new SomethingDoer(),0, measurmentPeriodMillis, TimeUnit.MILLISECONDS); After some event I should stop action, which Declared in run() method of the SomethingDoer , which implements Runnable . How can I do this? I can't shutdown executor, I should only revoke my periodic task. Can I use result.get() for this? And if I can, please tell me how it will work.

ThreadPoolExecutor源码详解

☆樱花仙子☆ 提交于 2019-12-15 11:12:57
【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>> 我之前一篇文章谈到了ThreadPoolExecutor的作用( http://my.oschina.net/xionghui/blog/494004 ),这篇文章介绍下它的原理,并根据原理分析下它的实现源码。 我们先来查看一下ThreadPoolExecutor API,看看它能实现什么功能,然后看看它是怎么实现这些功能的。 ThreadPoolExecutor API ThreadPoolExecutor API比较长,这里列出几个关键点: 核心和最大池大小:如果运行的线程少于 corePoolSize,则创建新线程来处理请求(即一个Runnable实例),即使其它线程是空闲的。如果运行的线程多于 corePoolSize 而少于 maximumPoolSize,则仅当队列满时才创建新线程。 保持活动时间:如果池中当前有多于 corePoolSize 的线程,则这些多出的线程在空闲时间超过 keepAliveTime 时将会终止。 排队: 如果运行的线程等于或多于 corePoolSize,则 Executor 始终首选将请求加入队列BlockingQueue,而不添加新的线程。 被拒绝的任务:当 Executor 已经关闭,或者队列已满且 线程数量达到 maximumPoolSize时(即线程池饱和了)

How to access the underlying queue of a ThreadpoolExecutor in a thread safe way

我的未来我决定 提交于 2019-12-12 01:06:20
问题 The getQueue() method provides access to the underlying blocking queue in the ThreadPoolExecutor, but this does not seem to be safe. A traversal over the queue returned by this function might miss updates made to the queue by the ThreadPoolExecutor. "Method getQueue() allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged." What would you do if you wanted to traverse the workQueue used by the

How to know when a thread stops or is stopped?

我是研究僧i 提交于 2019-12-11 12:34:21
问题 I have the next code: Executor exe = Executors.newFixedThreadPool(20); while (true) { try { exe.execute(new DispatcherThread(serverSocket.accept())); continue; } catch (SocketException sExcp) { System.exit(-1); } catch (Exception excp) { System.exit(-1); } } For each DispatcherThread I create a connection to the database (it means I have 20 connections), what I need to know is how I can close the connection to the database when the thread is stopped or it stops or finishes its flow. 回答1: You

ScheduledThreadPoolExecutors and custom queue

痴心易碎 提交于 2019-12-10 15:20:32
问题 If I use a ThreadPoolExecutor I have a variety of constructors and I can pass/use my own queue for the pool's work queue. Now I see that a ScheduledThreadPoolExecutor is a subclass of ThreadPoolExecutor but the constructors are much less. Is there a way to use a ScheduledThreadPoolExecutor and still use my own work queue? 回答1: You can extend ScheduledThreadPoolExecutor class and use a different queue then the DelayedWorkQueue that is bound to the current ScheduledThreadPoolExecutor