Callable, Future, simple to use thread pool

Callable, Future and thread pool

Create a new thread in three ways, 继承Threadand 实现Runnable接口both ways are no return value, so when we want to get the child thread the results can only be set to share data, but also need to consider synchronization problem, too much trouble. The Callable Interface is the solution of this problem.

Callable

Callable and Runnable similar, are only one way of iconic Interface : V call()just Callable there is a return value, and declare an exception Expection, that is, when computing the normal returns v, calculated error exception is thrown.
Callable single and have nothing to say, the interface generally with the Futureinterface to use.

Future interfaces

Future Callable interface tasks are processed, there are a method of finishing operations:

//获取结果,若无结果会阻塞至异步计算完成
V get()
//获取结果,超时返回null
V get(long timeOut, TimeUnit unit)
//执行结束(完成/取消/异常)返回true
boolean isDone()
//任务完成前被取消返回true
boolean isCancelled()
//取消任务,未开始或已完成返回false,参数表示是否中断执行中的线程
boolean cancel(boolean mayInterruptRunning)

Among them, for the boolean cancel(boolean mayInterruptRunning)method of argument:
Simply put, passing false parameters can only cancel the task has not yet started, if the task has already begun, became its run down.
When you create a Future instance, the task may have the following three states:
a standby state. At this time calling cancel () method is whether true or false will pass marked for cancellation, the task is still saved in the task queue, but when the turn will skip this task runs.
finished condition. In this case cancel () has no effect, because the task has been completed.
Operation. At this time passing in true interrupt the task being performed, passing false is not interrupted.

Future implementations subclass FutureTask<V>, i.e., the class implements the interface Future, also implements Runnable interface, thus Callable FutureTask be used with:

Callable<Integer> c = ()->{
    Thread.sleep(3000);//模拟计算
    return 100;//返回计算结果
};
//实例化FutureTask,注意这里不能使用Future的多态形式,因为只有FutureTask实现了Runnable接口
FutureTask<Integer> ft = new FutureTask<>(c);
//启动线程
new Thread(ft).start();
//获取计算结果,注意这里会阻塞
System.out.println(ft.get());

FutureTask provides two constructors:

//上例使用的就是这个,参数为Callable
public FutureTask(Callable<V> callable) {
}
//当Runnable执行成功时返回result(这有个毛用啊。。。)
public FutureTask(Runnable runnable, V result) {
}

FutureTask can easily start a thread.

Thread Pool

In addition to using FutureTask, also can be used Callable + Future + 线程池to perform Callable way:

Callable<Integer> c = ()->{
    Thread.sleep(3000);
    return 100;
};
//构建定长线程池
ExecutorService service = Executors.newFixedThreadPool(10);
//在线程池中提交Callable时会返回Future对象
Future<Integer> future = service.submit(c);
System.out.println(future.get());

The example of the thread pool to create a way for convenience only, at the Ali Developer's Handbook requirements:

[Mandatory] thread pool Executors are not allowed to create, but by ThreadPoolExecutor way, this approach allows the students to write more explicit operating rules thread pool, to avoid the risk of resource depletion.
Description: Executors drawbacks thread pool objects returned as follows:
. 1) and FixedThreadPool SingleThreadPool:
allowable request queue length Integer.MAX_VALUE, may accumulate a large number of requests, thereby causing OOM.
2) CachedThreadPool and ScheduledThreadPool:
allow the number of threads to create Integer.MAX_VALUE, may create a large number of threads, resulting OOM.

For several thread pool Executors provide are:

newSingleThreadExecutor
create a single-threaded thread pool. This is only a thread pool thread work, which is equivalent to a single-threaded serial execution of all tasks. If this thread only because of abnormal termination, then there will be a new thread to replace it.
This thread pool to ensure that the order of execution of all tasks presented to the order of tasks.

new ThreadPoolExecutor(1, 1,0L,TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>())

newFixedThreadPool
create a thread pool of fixed size. Each time you submit a task to create a thread, until the thread pool thread to reach the maximum size. Once the size of the thread pool reaches the maximum will remain unchanged, because if a thread execution abnormal end, the thread pool would add a new thread.

new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());

newCachedThreadPool
create a cached thread pool. If the size of the thread pool threads exceeds the processing tasks required, it will recover partially free (60 seconds does not perform the task) threads, when the number of tasks, this thread pool and intelligently add a new thread to handle the task.
This thread pool do not restrict the size of the thread pool, thread pool thread maximum size depends entirely on the size of the operating system (or JVM) that can be created.

new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>());

newScheduledThreadPool
create a fixed-size thread pool to support regular and periodic task execution. In addition to performing and newFixedThreadPool substantially the same delay, the timing can be used to perform tasks

The above four ways only more convenient, Ali manual requires developers can not use these methods, check out the thread pool the way Ali requirements:

public ThreadPoolExecutor(
    int corePoolSize,
    int maximumPoolSize,
    long keepAliveTime,
    TimeUnit unit,
    BlockingQueue<Runnable> workQueue,
    ThreadFactory threadFactory,
    RejectedExecutionHandler handler
) 

Parameters are as follows:

  • corePoolSize - the size of the thread pool Core pool.
  • maximumPoolSize - The maximum number of threads in the thread pool.
  • keepAliveTime - When the number of threads is greater than the core, this task is waiting for a new excess idle threads before terminating the longest time.
  • unit - keepAliveTime time unit.
  • workQueue - used to store queue waiting to execute the task.
  • threadFactory - thread factory.
  • handler - rejection policy

1 concerns the size of the thread pool
thread pool threads have a set of two numbers, a pool of threads for the number of cores, a maximum number of threads.
After you create a thread pool, by default, the thread pool and no thread, wait until the task was to create a thread to perform the task, unless you call the prestartAllCoreThreads () or prestartCoreThread () method
the number of threads created equal when corePoolSize time, It will join the blocking queue settings. When the queue is full, it will create a thread to perform tasks until the number of threads in the pool is equal to maximumPoolSize.
Concern 2 proper blocking queue
java.lang.IllegalStateException: Queue full
method throws an exception returns the special value has been blocked out and exit
the insertion method add (e) offer (e) put (e) offer (e, time, unit)
is removed method remove () poll () take ( ) poll (time, unit)
inspection method Element () PEEK ()
ArrayBlockingQueue with: an array of structures bounded blocking queue.
LinkedBlockingQueue: a linked list of structures bounded blocking queue.
PriorityBlockingQueue: a support prioritization of unbounded blocking queue.
DelayQueue: Use a priority queue unbounded blocking queue implementation.
SynchronousQueue: a blocking queue element is not stored.
LinkedTransferQueue: a list structure consisting of unbounded blocking queue.
LinkedBlockingDeque: a linked list structure consisting of two-way blocking queue.
3 focus explicitly rejected the policy
ThreadPoolExecutor.AbortPolicy: discard task and throw
RejectedExecutionException exception. (Default)
ThreadPoolExecutor.DiscardPolicy: the task is discarded, but does not throw an exception.
ThreadPoolExecutor.DiscardOldestPolicy: discard the foremost task queue, and then try to perform the task (Repeat this process) again
ThreadPoolExecutor.CallerRunsPolicy: This task is handled by the calling thread


reference

Guess you like

Origin www.cnblogs.com/lixin-link/p/11128487.html