ThreadPoolExecutor to use the thread pool

The method we achieve through inheritance Thread class and implement runnable interface or callable interfaces in three ways.

Inherit the Thread class actually implements runnable interface is inherited class is to achieve run () method, the method call by start ().

The callable interface is a part of Executor

The difference compared with the Runnable interface functions are:
(1) .Callable task may be provided at the end of a return value, the function is not Runnable 
(2) .Callable the call () method can throw an exception, and the Runnable run () method throws an exception can not 
(3). Callable operation can get a Future object, exclusive Future represents the result of an asynchronous computation, it provides a method of checking computation is complete. Since the thread is an asynchronous computation model, and therefore can not be obtained from another thread function 
 return values, in this case, it can be used to monitor the target thread Future situation calls call () method, put the call Future of get () method to getting results, the current thread will block, know call () method returns the end result. 

We can use multiple threads to achieve optimal efficiency, however, the more the thread is not better, too many threads, creation and destruction will consume system resources, nor easy to manage.

In addition, multi-threaded concurrency problems can also cause excessive number of concurrent threads, seize system resources causing obstruction.

   We will thread into the thread pool, to be managed by the thread pool threads can be multiplexed buffer thread pool thread, so that you do not often go to creating and destroying threads, and thus save the resources of the system.

The number of thread pool threads can effectively control the concurrency, multithreading can solve concurrency problems caused.

 

ThreadPoolExecutor

Java provides ThreadPoolExecutor thread pool class, he's the constructor has four different main parameters

 

 

 

 

 

corePoolSize for the thread pool maximum number of kernel threads

maximumPoolSize the maximum number of threads in the pool

When keepAliveTime when the number of active threads is greater than the core number of threads, the excess idle threads maximum survival time

unit survival time unit

workQueue store thread work queue

handler: thread bounds and queue capacities handler task (denial policy)

 

When the thread into the thread pool, when the number of threads have been equal to the maximum number of kernel threads, this thread will be placed in a queue of threads which, wait for the calling thread.

The maximum number of threads in the thread pool (total number of threads, maximumPoolSize) = number of cores (corePoolSize) non-core number of threads in the thread +

The core threads are never discarded recovery (even if not the core thread work) thread pool, non-core thread is more than a certain time (keepAliverTime) then will be discarded

 

Excutors Tools

java provides Excutors tools for about small projects, for some large programs still need to create your own ThreadPoolExecutor class, because Excutors may cause OOM (heap memory overflow)

FixedThreadPool and SingleThreadExecutor: request is allowed queue length Integer.MAX_VALUE, may accumulate a large number of requests, thereby causing OOM.
CachedThreadPool and ScheduledThreadPool: allows you to create a number of threads to Integer.MAX_VALUE, may create a large number of threads, resulting OOM.
method Explanation
newFixedThreadPool(int nThreads) Create a fixed-size thread pool
newSingleThreadExecutor () Creating a thread pool thread only
newCachedThreadPool() The maximum number of threads to create a thread pool limitation, any task will be executed immediately submitted
newScheduledThreadPool(int nThreads) Create a support timing or delayed periodic tasks defined number of threads in the thread pool
newSingleThreadScheduledExecutor () Create a support regular, periodic or delay the task of a single thread pool thread

 

 

Get the results from the thread pool

把线程提交给线程池中,有两种方法,一种是submit,另外一种则是execute

   execute没有返回值,性能会好很多,submit返回一个Future对象,如果想知道线程结果就使用submit提交,而且它能在主线程中通过Future的get方法捕获线程中的异常。

这两种方法的参数必须要实现runnable接口或者是callable对象

 线程池的处理结果、以及处理过程中的异常都被包装到Future中,并在调用Future.get()方法时获取,执行过程中的异常会被包装成ExecutionException。

关闭线程池

可以通过shutdown()或者shutdownNow()方法

shutdown() :   不再接受新的任务,之前提交的任务等执行结束再关闭线程池

shutdownNow() :不再接受新的任务,试图停止池中的任务再关闭线程池,返回所有未处理的线程list列表。

 

Semaphore 的使用方式

Semaphore 是 synchronized 的加强版,作用是控制线程的并发数量。(并发控制信号量)

我们可以在主要执行任务的call()方法或者run()方法中使用semaphore来控制并发。

semaphore的构造方法有两个

 

 第一个构造方法的参数为同一时刻允许线程进入的个数,如果为1,就相当于单个线程。

第二个构造方法的参数为线程公平性isFair

 isFair 的意思就是,是否公平,获得锁的顺序与线程启动顺序有关,就是公平,先启动的线程,先获得锁。isFair 不能100% 保证公平,只能是大概率公平。

 isFair 为 true,则表示公平,先启动的线程先获得锁。

在 semaphore.acquire() 和 semaphore.release()之间的代码,同一时刻只允许制定个数的线程进入, 因为semaphore的构造方法是1,则同一时刻只允许一个线程进入,其他线程只能等待。

acquire:

 

 

Guess you like

Origin www.cnblogs.com/oyjg/p/11951058.html