Callable和Future和FutureTask

Callable

Callable 位于 java.util.concurrent 包下,它也是一个接口,在它里面也只声明了一个方法,只不过这个方法叫做 call()

  1. public interface Callable<V> {
  2. /**
  3. * Computes a result, or throws an exception if unable to do so.
  4. *
  5. * @return computed result
  6. * @throws Exception if unable to compute a result
  7. */
  8. V call() throws Exception;
  9. }

可以看到,这是一个泛型接口,call() 函数返回的类型就是传递进来的V类型。

那么怎么使用 Callable 呢?一般情况下是配合 ExecutorService 来使用的,在 ExecutorService 接口中声明了若干个 submit() 方法的重载版本:

  1. <T> Future<T> submit(Callable<T> task);
  2. <T> Future<T> submit(Runnable task, T result);
  3. Future<?> submit(Runnable task);

第一个 submit 方法里面的参数类型就是 Callable

暂时只需要知道 Callable 一般是和 ExecutorService 配合来使用的,具体的使用方法讲在后面讲述。

Future

Future 就是对于具体的 Runnable 或者 Callable 任务的执行结果进行取消、查询是否完成、获取结果。必要时可以通过 get() 获取执行结果,该方法会阻塞直到任务返回结果。

Future 类位于 java.util.concurrent 包下,它是一个接口:

  1. public interface Future<V> {
  2. /**
  3. * Attempts to cancel execution of this task. This attempt will
  4. * fail if the task has already completed, has already been cancelled,
  5. * or could not be cancelled for some other reason. If successful,
  6. * and this task has not started when {@code cancel} is called,
  7. * this task should never run. If the task has already started,
  8. * then the {@code mayInterruptIfRunning} parameter determines
  9. * whether the thread executing this task should be interrupted in
  10. * an attempt to stop the task.
  11. *
  12. * <p>After this method returns, subsequent calls to {@link #isDone} will
  13. * always return {@code true}. Subsequent calls to {@link #isCancelled}
  14. * will always return {@code true} if this method returned {@code true}.
  15. *
  16. * @param mayInterruptIfRunning {@code true} if the thread executing this
  17. * task should be interrupted; otherwise, in-progress tasks are allowed
  18. * to complete
  19. * @return {@code false} if the task could not be cancelled,
  20. * typically because it has already completed normally;
  21. * {@code true} otherwise
  22. */
  23. boolean cancel(boolean mayInterruptIfRunning);
  24. /**
  25. * Returns {@code true} if this task was cancelled before it completed
  26. * normally.
  27. *
  28. * @return {@code true} if this task was cancelled before it completed
  29. */
  30. boolean isCancelled();
  31. /**
  32. * Returns {@code true} if this task completed.
  33. *
  34. * Completion may be due to normal termination, an exception, or
  35. * cancellation -- in all of these cases, this method will return
  36. * {@code true}.
  37. *
  38. * @return {@code true} if this task completed
  39. */
  40. boolean isDone();
  41. /**
  42. * Waits if necessary for the computation to complete, and then
  43. * retrieves its result.
  44. *
  45. * @return the computed result
  46. * @throws CancellationException if the computation was cancelled
  47. * @throws ExecutionException if the computation threw an
  48. * exception
  49. * @throws InterruptedException if the current thread was interrupted
  50. * while waiting
  51. */
  52. V get() throws InterruptedException, ExecutionException;
  53. /**
  54. * Waits if necessary for at most the given time for the computation
  55. * to complete, and then retrieves its result, if available.
  56. *
  57. * @param timeout the maximum time to wait
  58. * @param unit the time unit of the timeout argument
  59. * @return the computed result
  60. * @throws CancellationException if the computation was cancelled
  61. * @throws ExecutionException if the computation threw an
  62. * exception
  63. * @throws InterruptedException if the current thread was interrupted
  64. * while waiting
  65. * @throws TimeoutException if the wait timed out
  66. */
  67. V get(long timeout, TimeUnit unit)
  68. throws InterruptedException, ExecutionException, TimeoutException;
  69. }

Future 接口中声明了5个方法,下面依次解释每个方法的作用:

cancel()

用来取消任务,如果取消任务成功则返回true,如果取消任务失败则返回false。参数 mayInterruptIfRunning 表示是否允许取消正在执行却没有执行完毕的任务,如果设置true,则表示可以取消正在执行过程中的任务。如果任务已经完成,则无论 mayInterruptIfRunning 为true还是false,此方法肯定返回false,即如果取消已经完成的任务会返回false;如果任务正在执行,若 mayInterruptIfRunning 设置为true,则返回true,若mayInterruptIfRunning 设置为false,则返回false;如果任务还没有执行,则无论 mayInterruptIfRunning 为true还是false,肯定返回true。

isCancelled()

表示任务是否被取消成功,如果在任务正常完成前被取消成功,则返回 true。

isDone()

表示任务是否已经完成,若任务完成,则返回true;

get()

用来获取执行结果,这个方法会产生阻塞,会一直等到任务执行完毕才返回;

get(long timeout, TimeUnit unit)

用来获取执行结果,如果在指定时间内,还没获取到结果,就直接抛出TimeoutException。

FutureTask

Future提供了三种功能:

  • 判断任务是否完成;
  • 能够中断任务;
  • 能够获取任务执行结果。

Future 只是一个接口,是无法直接用来创建对象使用的,因此就有了下面的 FutureTaskExecutorService 返回的实际类型就是 FutureTask。我们先来看一下 FutureTask 的实现:

  1. public class FutureTask<V> implements RunnableFuture<V>

FutureTask 类实现了 RunnableFuture 接口,我们看一下 RunnableFuture 接口的实现:

  1. public interface RunnableFuture<V> extends Runnable, Future<V>

可以看出 RunnableFuture 继承了 Runnable 接口和 Future 接口,而 FutureTask 实现了 RunnableFuture 接口。所以它既可以作为 Runnable 被线程执行,又可以作为Future 得到 Callable 的返回值。

FutureTask 提供了2个构造器:

  1. public FutureTask(Callable<V> callable);
  2. public FutureTask(Runnable runnable, V result);

使用示例

使用Callable+Future获取执行结果

  1. public class Test {
  2. public static void main(String[] args) {
  3. ExecutorService executor = Executors.newCachedThreadPool();
  4. Task task = new Task();
  5. Future<Integer> result = executor.submit(task);
  6. executor.shutdown();
  7. try {
  8. Thread.sleep(1000);
  9. } catch (InterruptedException e1) {
  10. e1.printStackTrace();
  11. }
  12. System.out.println("主线程在执行任务");
  13. try {
  14. System.out.println("task运行结果"+result.get());
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. } catch (ExecutionException e) {
  18. e.printStackTrace();
  19. }
  20. System.out.println("所有任务执行完毕");
  21. }
  22. }
  23. class Task implements Callable<Integer>{
  24. @Override
  25. public Integer call() throws Exception {
  26. System.out.println("子线程在进行计算");
  27. Thread.sleep(3000);
  28. int sum = 0;
  29. for(int i=0;i<100;i++)
  30. sum += i;
  31. return sum;
  32. }
  33. }

使用Callable+FutureTask获取执行结果

  1. public class Test {
  2. public static void main(String[] args) {
  3. // 第一种方式
  4. ExecutorService executor = Executors.newCachedThreadPool();
  5. Task task = new Task();
  6. FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
  7. executor.submit(futureTask);
  8. executor.shutdown();
  9. // 第二种方式,注意这种方式和第一种方式效果是类似的,
  10. // 只不过一个使用的是ExecutorService,一个使用的是Thread
  11. /*
  12. Task task = new Task();
  13. FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
  14. Thread thread = new Thread(futureTask);
  15. thread.start();
  16. */
  17. try {
  18. Thread.sleep(1000);
  19. } catch (InterruptedException e1) {
  20. e1.printStackTrace();
  21. }
  22. System.out.println("主线程在执行任务");
  23. try {
  24. System.out.println("task运行结果"+futureTask.get());
  25. } catch (InterruptedException e) {
  26. e.printStackTrace();
  27. } catch (ExecutionException e) {
  28. e.printStackTrace();
  29. }
  30. System.out.println("所有任务执行完毕");
  31. }
  32. }
  33. class Task implements Callable<Integer>{
  34. @Override
  35. public Integer call() throws Exception {
  36. System.out.println("子线程在进行计算");
  37. Thread.sleep(3000);
  38. int sum = 0;
  39. for(int i=0;i<100;i++)
  40. sum += i;
  41. return sum;
  42. }
  43. }

线程池

Executors

Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes defined in this package. This class supports the following kinds of methods:

  • Methods that create and return an ExecutorService set up with commonly useful configuration settings.
  • Methods that create and return a ScheduledExecutorService set up with commonly useful configuration settings.
  • Methods that create and return a “wrapped” ExecutorService, that disables reconfiguration by making implementation-specific methods inaccessible.
  • Methods that create and return a ThreadFactory that sets newly created threads to a known state.
  • Methods that create and return a Callable out of other closure-like(类似闭包) forms, so they can be used in execution methods requiring Callable.

Java并发-06-线程池 - 图1

Executor

  1. public interface Executor {
  2. /**
  3. * Executes the given command at some time in the future. The command
  4. * may execute in a new thread, in a pooled thread, or in the calling
  5. * thread, at the discretion of the {@code Executor} implementation.
  6. *
  7. * @param command the runnable task
  8. * @throws RejectedExecutionException if this task cannot be
  9. * accepted for execution
  10. * @throws NullPointerException if command is null
  11. */
  12. void execute(Runnable command);
  13. }

An object that executes submitted Runnable tasks. This interface provides a way of decoupling(解耦) task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc. An Executor is normally used instead of explicitly creating threads. For example, rather than invoking new Thread(new(RunnableTask())).start() for each of a set of tasks, you might use:

However, the Executor interface does not strictly require that execution be asynchronous. In the simplest case, an executor can run the submitted task immediately in the caller’s thread:

More typically, tasks are executed in some thread other than the caller’s thread. The executor below spawns(产生) a new thread for each task.

Many Executor implementations impose(强加) some sort of limitation on how and when tasks are scheduled. The executor below serializes the submission of tasks to a second executor, illustrating(解释) a composite(复合的) executor.

The Executor implementations provided in this package implement ExecutorService, which is a more extensive interface. The ThreadPoolExecutor class provides an extensible thread pool implementation. The Executors class provides convenient factory methods for these Executors.

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

  1. Executor executor = anExecutor;
  2. executor.execute(new RunnableTask1());
  3. executor.execute(new RunnableTask2());
  4. ...
  1. class DirectExecutor implements Executor {
  2. public void execute(Runnable r) {
  3. r.run();
  4. }
  5. }
  1. class ThreadPerTaskExecutor implements Executor {
  2. public void execute(Runnable r) {
  3. new Thread(r).start();
  4. }
  5. }
  1. class SerialExecutor implements Executor {
  2. final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
  3. final Executor executor;
  4. Runnable active;
  5. SerialExecutor(Executor executor) {
  6. this.executor = executor;
  7. }
  8. public synchronized void execute(final Runnable r) {
  9. tasks.offer(new Runnable() {
  10. public void run() {
  11. try {
  12. r.run();
  13. } finally {
  14. scheduleNext();
  15. }
  16. }
  17. });
  18. if (active == null) {
  19. scheduleNext();
  20. }
  21. }
  22. protected synchronized void scheduleNext() {
  23. if ((active = tasks.poll()) != null) {
  24. executor.execute(active);
  25. }
  26. }
  27. }

ExecutorService

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown method will allow previously submitted tasks to execute before terminating, while the shutdownNow method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation(开垦,填海) of its resources.

Method submit extends base method Executor.execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a collection of tasks and then waiting for at least one, or all, to complete. (Class ExecutorCompletionService can be used to write customized variants of these methods.)

The Executors class provides factory methods for the executor services provided in this package.

Usage Examples

Here is a sketch(草图) of a network service in which threads in a thread pool service incoming requests. It uses the preconfigured Executors.newFixedThreadPool factory method:

The following method shuts down an ExecutorService in two phases, first by calling shutdown to reject incoming tasks, and then calling shutdownNow, if necessary, to cancel any lingering tasks:

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

  1. void shutdown();
  2. // return a list of the tasks that were awaiting execution.
  3. List<Runnable> shutdownNow();
  1. class NetworkService implements Runnable {
  2. private final ServerSocket serverSocket;
  3. private final ExecutorService pool;
  4. public NetworkService(int port, int poolSize)
  5. throws IOException {
  6. serverSocket = new ServerSocket(port);
  7. pool = Executors.newFixedThreadPool(poolSize);
  8. }
  9. public void run() { // run the service
  10. try {
  11. for (;;) {
  12. pool.execute(new Handler(serverSocket.accept()));
  13. }
  14. } catch (IOException ex) {
  15. pool.shutdown();
  16. }
  17. }
  18. }
  19. class Handler implements Runnable {
  20. private final Socket socket;
  21. Handler(Socket socket) { this.socket = socket; }
  22. public void run() {
  23. // read and service request on socket
  24. }
  25. }
  1. void shutdownAndAwaitTermination(ExecutorService pool) {
  2. pool.shutdown(); // Disable new tasks from being submitted
  3. try {
  4. // Wait a while for existing tasks to terminate
  5. if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
  6. pool.shutdownNow(); // Cancel currently executing tasks
  7. // Wait a while for tasks to respond to being cancelled
  8. if (!pool.awaitTermination(60, TimeUnit.SECONDS))
  9. System.err.println("Pool did not terminate");
  10. }
  11. } catch (InterruptedException ie) {
  12. // (Re-)Cancel if current thread also interrupted
  13. pool.shutdownNow();
  14. // Preserve interrupt status
  15. Thread.currentThread().interrupt();
  16. }
  17. }

AbstractExecutorService

Provides default implementations of ExecutorService execution methods. This class implements the submit, invokeAny and invokeAll methods using a RunnableFuture returned by newTaskFor, which defaults to the FutureTask class provided in this package. For example, the implementation of submit(Runnable) creates an associated RunnableFuture that is executed and returned. Subclasses may override the newTaskFor methods to return RunnableFuture implementations other than FutureTask.

Extension example. Here is a sketch of a class that customizes ThreadPoolExecutor to use a CustomTask class instead of the default FutureTask:

  1. public class CustomThreadPoolExecutor extends ThreadPoolExecutor {
  2. static class CustomTask<V> implements RunnableFuture<V> {...}
  3. protected <V> RunnableFuture<V> newTaskFor(Callable<V> c) {
  4. return new CustomTask<V>(c);
  5. }
  6. protected <V> RunnableFuture<V> newTaskFor(Runnable r, V v) {
  7. return new CustomTask<V>(r, v);
  8. }
  9. // ... add constructors, etc.
  10. }

ThreadExecutorService

An ExecutorService that executes each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods.

Thread pools address two different problems: they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead(开销), and they provide a means of(一种手段) bounding(边界) and managing the resources, including threads, consumed when executing a collection of tasks. Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.

To be useful across a wide range of contexts, this class provides many adjustable parameters and extensibility hooks. However, programmers are urged to use the more convenient Executors factory methods Executors.newCachedThreadPool (unbounded thread pool, with automatic thread reclamation), Executors.newFixedThreadPool (fixed size thread pool) and Executors.newSingleThreadExecutor (single background thread), that preconfigure settings for the most common usage scenarios. Otherwise, use the following guide when manually configuring and tuning this class:

Core and maximum pool sizes

A ThreadPoolExecutor will automatically adjust the pool size (see getPoolSize) according to the bounds set by corePoolSize (see getCorePoolSize) and maximumPoolSize (see getMaximumPoolSize).

When a new task is submitted in method execute(Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full. By setting corePoolSize and maximumPoolSize the same, you create a fixed-size thread pool. By setting maximumPoolSize to an essentially unbounded value such as Integer.MAX_VALUE, you allow the pool to accommodate an arbitrary(任意的、专制的、随心所欲的) number of concurrent tasks. Most typically, core and maximum pool sizes are set only upon construction, but they may also be changed dynamically using setCorePoolSize and setMaximumPoolSize.

On-demand construction

By default, even core threads are initially created and started only when new tasks arrive, but this can be overridden dynamically using method prestartCoreThread or prestartAllCoreThreads. You probably want to prestart threads if you construct the pool with a non-empty queue.

Creating new threads

New threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory is used, that creates threads to all be in the same ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread’s name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks. Threads should possess(拥有) the “modifyThread” RuntimePermission. If worker threads or other threads using the pool do not possess this permission, service may be degraded(降级): configuration changes may not take effect in a timely(及时) manner(方式), and a shutdown pool may remain in a state in which termination is possible but not completed.

Keep-alive times

If the pool currently has more than corePoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime (see getKeepAliveTime(TimeUnit)). This provides a means of reducing resource consumption(消费) when the pool is not being actively used. If the pool becomes more active later, new threads will be constructed. This parameter can also be changed dynamically using method setKeepAliveTime(long, TimeUnit). Using a value of Long.MAX_VALUE TimeUnit.NANOSECONDS effectively disables idle threads from ever terminating prior to shut down. By default, the keep-alive policy applies only when there are more than corePoolSize threads. But method allowCoreThreadTimeOut(boolean) can be used to apply this time-out policy to core threads as well, so long as(只要) the keepAliveTime value is non-zero.

Queuing

Any BlockingQueue may be used to transfer and hold submitted tasks. The use of this queue interacts with pool sizing:

  • If fewer than corePoolSize threads are running, the Executor always prefers adding a new thread rather than queuing.
  • If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread.
  • If a request cannot be queued, a new thread is created unless this would exceed(超过) maximumPoolSize, in which case, the task will be rejected.

There are three general strategies for queuing:

  1. Direct handoffs. A good default choice for a work queue is a SynchronousQueue that hands off tasks to threads without otherwise holding them. Here, an attempt to queue a task will fail if no threads are immediately available to run it, so a new thread will be constructed. This policy avoids lockups(锁定) when handling sets of requests that might have internal dependencies. Direct handoffs generally require unbounded maximumPoolSizes to avoid rejection of new submitted tasks. This in turn admits the possibility of unbounded thread growth when commands continue to arrive on average faster than they can be processed.
  2. Unbounded queues. Using an unbounded queue (for example a LinkedBlockingQueue without a predefined capacity) will cause new tasks to wait in the queue when all corePoolSize threads are busy. Thus, no more than corePoolSize threads will ever be created. (And the value of the maximumPoolSize therefore doesn’t have any effect.) This may be appropriate when each task is completely independent of others, so tasks cannot affect each others execution; for example, in a web page server. While this style of queuing can be useful in smoothing out transient(短暂的) bursts(爆发) of requests, it admits the possibility of unbounded work queue growth when commands continue to arrive on average faster than they can be processed.
  3. Bounded queues. A bounded queue (for example, an ArrayBlockingQueue) helps prevent resource exhaustion when used with finite maximumPoolSizes, but can be more difficult to tune(调) and control. Queue sizes and maximum pool sizes may be traded off(权衡) for each other: Using large queues and small pools minimizes CPU usage, OS resources, and context-switching overhead, but can lead to artificially(人为的) low throughput. If tasks frequently block (for example if they are I/O bound), a system may be able to schedule time for more threads than you otherwise(相反的 adj.) allow. Use of small queues generally requires larger pool sizes, which keeps CPUs busier but may encounter unacceptable scheduling overhead, which also decreases throughput.

Rejected tasks

New tasks submitted in method execute(Runnable) will be rejected when the Executor has been shut down, and also when the Executor uses finite bounds for both maximum threads and work queue capacity, and is saturated(饱和的). In either case, the execute method invokes the RejectedExecutionHandler.rejectedExecution(Runnable, ThreadPoolExecutor) method of its RejectedExecutionHandler. Four predefined handler policies are provided:

  • In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.
  • In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.
  • In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.
  • In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

It is possible to define and use other kinds of RejectedExecutionHandler classes. Doing so requires some care especially when policies are designed to work only under particular capacity or queuing policies.

Hook methods

This class provides protected overridable beforeExecute(Thread, Runnable) and afterExecute(Runnable, Throwable) methods that are called before and after execution of each task.

These can be used to manipulate(操纵) the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated can be overridden to perform any special processing that needs to be done once the Executor has fully terminated.

If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly(意外的) terminate.

Queue maintenance

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. Two supplied methods, remove(Runnable) and purge are available to assist in storage reclamation(开垦) when large numbers of queued tasks become cancelled.

Finalization

A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. If you would like to ensure that unreferenced pools are reclaimed(回收) even if users forget to call shutdown, then you must arrange that unused threads eventually die, by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting allowCoreThreadTimeOut(boolean).

Extension example. Most extensions of this class override one or more of the protected hook methods. For example, here is a subclass that adds a simple pause/resume feature:

  1. class PausableThreadPoolExecutor extends ThreadPoolExecutor {
  2. private boolean isPaused;
  3. private ReentrantLock pauseLock = new ReentrantLock();
  4. private Condition unpaused = pauseLock.newCondition();
  5. public PausableThreadPoolExecutor(...) { super(...); }
  6. protected void beforeExecute(Thread t, Runnable r) {
  7. super.beforeExecute(t, r);
  8. pauseLock.lock();
  9. try {
  10. while (isPaused) unpaused.await();
  11. } catch (InterruptedException ie) {
  12. t.interrupt();
  13. } finally {
  14. pauseLock.unlock();
  15. }
  16. }
  17. public void pause() {
  18. pauseLock.lock();
  19. try {
  20. isPaused = true;
  21. } finally {
  22. pauseLock.unlock();
  23. }
  24. }
  25. public void resume() {
  26. pauseLock.lock();
  27. try {
  28. isPaused = false;
  29. unpaused.signalAll();
  30. } finally {
  31. pauseLock.unlock();
  32. }
  33. }
  34. }

ThreadGroup

A thread group represents a set of threads. In addition, a thread group can also include other thread groups. The thread groups form a tree in which every thread group except the initial thread group has a parent.

A thread is allowed to access information about its own thread group, but not to access information about its thread group’s parent thread group or any other thread groups.

线程组的出现是为了更方便地管理线程。

线程组是父子结构的,一个线程组可以集成其他线程组,同时也可以拥有其他子线程组。从结构上看,线程组是一个树形结构,每个线程都隶属于一个线程组,线程组又有父线程组,这样追溯下去,可以追溯到一个根线程组——System线程组。

  1. public static void main(String[] args) {
  2. ThreadGroup mainThreadGroup = Thread.currentThread().getThreadGroup();
  3. ThreadGroup systenThreadGroup = mainThreadGroup.getParent();
  4. ThreadGroup parent = systenThreadGroup.getParent();
  5. System.out.println("systenThreadGroup name = " + systenThreadGroup.getName());
  6. System.out.println("mainThreadGroup name = " + mainThreadGroup.getName());
  7. System.out.println(parent.getName());
  8. }
  9. // systenThreadGroup name = system
  10. // mainThreadGroup name = main
  11. // Exception in thread "main" java.lang.NullPointerException
  12. // at Test.main(Test.java:9)

java.lang.ThreadGroup 提供了两个构造函数:

Constructor Description
ThreadGroup(String name) 根据线程组名称创建线程组,其父线程组为main线程组
ThreadGroup(ThreadGroup parent, String name) 根据线程组名称创建线程组,其父线程组为指定的parent线程组

自定义异常处理

  1. public class ThreadGroupDemo {
  2. public static void main(String[] args) {
  3. ThreadGroup threadGroup1 = new ThreadGroup("group1") {
  4. // 继承ThreadGroup并重新定义以下方法
  5. // 在线程成员抛出unchecked exception
  6. // 会执行此方法
  7. public void uncaughtException(Thread t, Throwable e) {
  8. System.out.println(t.getName() + ": " + e.getMessage());
  9. }
  10. };
  11. // 这个线程是threadGroup1的一员
  12. Thread thread1 = new Thread(threadGroup1, new Runnable() {
  13. public void run() {
  14. // 抛出unchecked异常
  15. System.out.println(1 / 0);
  16. }
  17. });
  18. thread1.start();
  19. }
  20. }

自定义线程池使用

ThreadPoolExecutor 使用其内部池中的线程执行给定任务(Callable 或者 Runnable)。ThreadPoolExecutor 包含的线程池能够包含不同数量的线程。池中线程的数量由以下变量决定:

  • corePoolSize
  • maximumPoolSize

当一个任务委托给线程池时,如果池中线程数量低于 corePoolSize,一个新的线程将被创建,即使池中可能尚有空闲线程。如果内部任务队列已满,而且有 corePoolSize 个线程正在运行,但是运行线程的数量低于maximumPoolSize,一个新的线程将被创建去执行该任务。

  1. public ThreadPoolExecutor(int corePoolSize,
  2. int maximumPoolSize,
  3. long keepAliveTime,
  4. TimeUnit unit,
  5. BlockingQueue<Runnable> workQueue,
  6. ThreadFactory threadFactory,
  7. RejectedExecutionHandler handler);
  • corePoolSize:线程池核心线程数(平时保留的线程数)
  • maximumPoolSize:线程池最大线程数(当workQueue都放不下时,启动新线程,最大线程数)
  • keepAliveTime:超出corePoolSize数量的线程的保留时间。
  • unit:keepAliveTime单位
  • workQueue:阻塞队列,存放来不及执行的线程
    • ArrayBlockingQueue:构造函数一定要传大小
    • LinkedBlockingQueue:构造函数不传大小会默认为(Integer.MAX_VALUE ),当大量请求任务时,容易造成 内存耗尽。
    • SynchronousQueue:同步队列,一个没有存储空间的阻塞队列 ,将任务同步交付给工作线程。
    • PriorityBlockingQueue:优先队列
  • threadFactory:线程工厂
  • handler:饱和策略
    • AbortPolicy(默认):直接抛弃
    • CallerRunsPolicy:用调用者的线程执行任务
    • DiscardOldestPolicy:抛弃队列中最久的任务
    • DiscardPolicy:抛弃当前任务

阿里巴巴开发手册

线程池不使用 Executors 去创建,而是通过 ThreadPoolExecutor 的方式,这样的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。

说明: Executors 返回的线程池对象的弊端如下:

  1. FixedThreadPool 和 SingleThreadPool : 允许的请求队列长度为 Integer.MAX_VALUE ,可能会堆积大量的请求,从而导致 OOM 。
  2. CachedThreadPool 和 ScheduledThreadPool : 允许的创建线程数量为 Integer.MAX_VALUE ,可能会创建大量的线程,从而导致 OOM。

自定义ThreadFactory

An object that creates new threads on demand. Using thread factories removes hardwiring of calls to new Thread, enabling applications to use special thread subclasses, priorities, etc.

The simplest implementation of this interface is just:

The Executors.defaultThreadFactory method provides a more useful simple implementation, that sets the created thread context to known values before returning it.

  1. class SimpleThreadFactory implements ThreadFactory {
  2. public Thread newThread(Runnable r) {
  3. return new Thread(r);
  4. }
  5. }

DefaultThreadFactory

  1. static class DefaultThreadFactory implements ThreadFactory {
  2. private static final AtomicInteger poolNumber = new AtomicInteger(1);
  3. private final ThreadGroup group;
  4. private final AtomicInteger threadNumber = new AtomicInteger(1);
  5. private final String namePrefix;
  6. DefaultThreadFactory() {
  7. SecurityManager s = System.getSecurityManager();
  8. group = (s != null) ? s.getThreadGroup() :
  9. Thread.currentThread().getThreadGroup();
  10. namePrefix = "pool-" + poolNumber.getAndIncrement() + "-thread-";
  11. }
  12. public Thread newThread(Runnable r) {
  13. Thread t = new Thread(group, r,
  14. namePrefix + threadNumber.getAndIncrement(),
  15. 0);
  16. if (t.isDaemon())
  17. t.setDaemon(false);
  18. if (t.getPriority() != Thread.NORM_PRIORITY)
  19. t.setPriority(Thread.NORM_PRIORITY);
  20. return t;
  21. }
  22. }

SecurityManager 获取的 ThreadGroup 如下:

  1. private static ThreadGroup getRootGroup() {
  2. ThreadGroup root = Thread.currentThread().getThreadGroup();
  3. while (root.getParent() != null) {
  4. root = root.getParent();
  5. }
  6. return root;
  7. }

DefaultThreadFactoryThreadGroup

  1. public static void main(String[] args) {
  2. ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
  3. 2,
  4. 2,
  5. 60,
  6. TimeUnit.SECONDS,
  7. new LinkedBlockingQueue<>(),
  8. Executors.defaultThreadFactory(),
  9. new ThreadPoolExecutor.AbortPolicy()
  10. );
  11. threadPoolExecutor.execute(new Thread() {
  12. @Override
  13. public void run() {
  14. System.out.println(this.getThreadGroup().getName()); // main
  15. }
  16. });
  17. }

自定义RejectedExecutionHandler

  1. /**
  2. * A handler for tasks that cannot be executed by a {@link ThreadPoolExecutor}.
  3. */
  4. public interface RejectedExecutionHandler {
  5. /**
  6. * Method that may be invoked by a {@link ThreadPoolExecutor} when
  7. * {@link ThreadPoolExecutor#execute execute} cannot accept a
  8. * task. This may occur when no more threads or queue slots are
  9. * available because their bounds would be exceeded, or upon
  10. * shutdown of the Executor.
  11. *
  12. * <p>In the absence of other alternatives, the method may throw
  13. * an unchecked {@link RejectedExecutionException}, which will be
  14. * propagated to the caller of {@code execute}.
  15. *
  16. * @param r the runnable task requested to be executed
  17. * @param executor the executor attempting to execute this task
  18. * @throws RejectedExecutionException if there is no remedy
  19. */
  20. void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
  21. }

测试

  1. public class T14_MyRejectedHandler {
  2. public static void main(String[] args) {
  3. ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1,
  4. 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(6),
  5. new MyThreadFactory(),
  6. new MyHandler());
  7. for (int i = 0; i < 100; i++) {
  8. threadPoolExecutor.submit(() -> {
  9. try {
  10. TimeUnit.SECONDS.sleep(100);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. });
  15. }
  16. }
  17. static class MyHandler implements RejectedExecutionHandler {
  18. private AtomicInteger count = new AtomicInteger(1);
  19. @Override
  20. public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
  21. System.out.println(r.getClass() + " " + count.get());
  22. count.incrementAndGet();
  23. }
  24. }
  25. static class MyThreadFactory implements ThreadFactory {
  26. public Thread newThread(Runnable r) {
  27. System.out.println("new Thread ... ");
  28. return new Thread(r);
  29. }
  30. }
  31. }

此时会发现,现在拒绝策略走的是我们的 MyHandler,输出的是类是:java.util.concurrent.FutureTask

执行流程

submit()

  1. public Future<?> submit(Runnable task) {
  2. if (task == null) throw new NullPointerException();
  3. RunnableFuture<Void> ftask = newTaskFor(task, null);
  4. execute(ftask);
  5. return ftask;
  6. }
  1. protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
  2. return new FutureTask<T>(runnable, value);
  3. }

submit() 方法里,我们提交的任务会被包装成一个 RunnableFuture,而 newTaskFor() 返回的真实类型就是我们上面测试输出的 FutureTask

ctl

The main pool control state, ctl, is an atomic integer packing two conceptual fields workerCount, indicating the effective number of threads runState, indicating whether running, shutting down etc.

In order to pack them into one int, we limit workerCount to (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2 billion) otherwise representable. If this is ever an issue in the future, the variable can be changed to be an AtomicLong, and the shift/mask constants below adjusted. But until the need arises, this code is a bit faster and simpler using an int.

The workerCount is the number of workers that have been permitted to start and not permitted to stop. The value may be transiently different from the actual number of live threads, for example when a ThreadFactory fails to create a thread when asked, and when exiting threads are still performing bookkeeping(簿记) before terminating. The user-visible pool size is reported as the current size of the workers set.

The runState provides the main lifecycle control, taking on values:

  • RUNNING: Accept new tasks and process queued tasks (初始状态)
  • SHUTDOWN: Don’t accept new tasks, but process queued tasks
  • STOP: Don’t accept new tasks, don’t process queued tasks, and interrupt in-progress tasks
  • TIDYING(整理): All tasks have terminated, workerCount is zero, the thread transitioning to state TIDYING will run the terminated() hook method
  • TERMINATED: terminated() has completed

The numerical order among these values matters(重要), to allow ordered comparisons. The runState monotonically increases over time, but need not hit(击中、到达) each state. The transitions are:

  • RUNNING -> SHUTDOWN: On invocation of shutdown(), perhaps implicitly(隐含的) in finalize()
  • (RUNNING or SHUTDOWN) -> STOP: On invocation of shutdownNow()
  • SHUTDOWN -> TIDYING: When both queue and pool are empty
  • STOP -> TIDYING: When pool is empty
  • TIDYING -> TERMINATED: When the terminated() hook method has completed

Threads waiting in awaitTermination() will return when the state reaches TERMINATED. Detecting the transition from SHUTDOWN to TIDYING is less straightforward than you’d like because the queue may become empty after non-empty and vice versa during SHUTDOWN state, but we can only terminate if, after seeing that it is empty, we see that workerCount is 0 (which sometimes entails a recheck — see below).

Java并发-06-线程池 - 图2

  1. public void execute(Runnable command) {
  2. if (command == null)
  3. throw new NullPointerException();
  4. /*
  5. * Proceed in 3 steps:
  6. *
  7. * 1. If fewer than corePoolSize threads are running, try to
  8. * start a new thread with the given command as its first
  9. * task. The call to addWorker atomically checks runState and
  10. * workerCount, and so prevents false alarms that would add
  11. * threads when it shouldn't, by returning false.
  12. *
  13. * 2. If a task can be successfully queued, then we still need
  14. * to double-check whether we should have added a thread
  15. * (because existing ones died since last checking) or that
  16. * the pool shut down since entry into this method. So we
  17. * recheck state and if necessary roll back the enqueuing if
  18. * stopped, or start a new thread if there are none.
  19. *
  20. * 3. If we cannot queue task, then we try to add a new
  21. * thread. If it fails, we know we are shut down or saturated
  22. * and so reject the task.
  23. */
  24. int c = ctl.get();
  25. // worker线程小于核心线程数,增加一个线程
  26. if (workerCountOf(c) < corePoolSize) {
  27. // 增加线程成功了,就可以返回
  28. if (addWorker(command, true))
  29. return;
  30. // 增加线程不成功,此时ctl会被更改
  31. c = ctl.get();
  32. }
  33. // 如果工作线程数大于等于核心线程数,线程池的状态是RUNNING,并且添加进队列成功
  34. if (isRunning(c) && workQueue.offer(command)) {
  35. // 由于在进入队列前后,线程可能会死掉或者线程池会shutdown,所以需要recheck
  36. // 比如在ctl获取之后,command进入队列前,队列的内容执行完毕,线程死掉。
  37. int recheck = ctl.get();
  38. // 如果线程池没有在运行(执行过shutdown),并且从任务队列中移除成功,reject此任务
  39. if (!isRunning(recheck) && remove(command))
  40. reject(command);
  41. // 如果线程池没在运行,但是移除失败,说明此任务已经被完成
  42. // 所以此处判断是够为0是由于,在线程池构造方法中,核心线程数允许为0,此时需要增加一个线程
  43. // 也就是corePoolSize为0且我们提交的是第一个任务的情况
  44. else if (workerCountOf(recheck) == 0)
  45. addWorker(null, false);
  46. }
  47. // 如果线程池不是运行状态,或者任务进入队列失败,则尝试创建worker执行任务。
  48. // 这儿有3点需要注意:
  49. // 1. 线程池不是运行状态时,addWorker内部会判断线程池状态
  50. // 2. addWorker第2个参数表示是否创建核心线程
  51. // 3. addWorker返回false,则说明任务执行失败,需要执行reject操作
  52. else if (!addWorker(command, false))
  53. reject(command);
  54. }

addWorker()

  1. /**
  2. * Checks if a new worker can be added with respect to current
  3. * pool state and the given bound (either core or maximum). If so,
  4. * the worker count is adjusted accordingly, and, if possible, a
  5. * new worker is created and started, running firstTask as its
  6. * first task. This method returns false if the pool is stopped or
  7. * eligible(合格、可以选) to shut down. It also returns false if the thread
  8. * factory fails to create a thread when asked. If the thread
  9. * creation fails, either due to the thread factory returning
  10. * null, or due to an exception (typically OutOfMemoryError in
  11. * Thread.start()), we roll back cleanly.
  12. *
  13. * @param firstTask the task the new thread should run first (or
  14. * null if none). Workers are created with an initial first task
  15. * (in method execute()) to bypass queuing when there are fewer
  16. * than corePoolSize threads (in which case we always start one),
  17. * or when the queue is full (in which case we must bypass queue).
  18. * Initially idle threads are usually created via
  19. * prestartCoreThread or to replace other dying workers.
  20. *
  21. * @param core if true use corePoolSize as bound, else
  22. * maximumPoolSize. (A boolean indicator is used here rather than a
  23. * value to ensure reads of fresh values after checking other pool
  24. * state).
  25. * @return true if successful
  26. */
  27. private boolean addWorker(Runnable firstTask, boolean core) {
  28. retry:
  29. for (;;) {
  30. int c = ctl.get();
  31. int rs = runStateOf(c);
  32. // 1. 线程池状态大于SHUTDOWN时,直接返回false
  33. // 2. 线程池状态等于SHUTDOWN,且firstTask不为null,直接返回false
  34. // 3. 线程池状态等于SHUTDOWN,且队列为空,直接返回false
  35. if (rs >= SHUTDOWN &&
  36. (rs != SHUTDOWN || firstTask != null || workQueue.isEmpty()))
  37. return false;
  38. // 能到达这一步的条件是线程池处于RUNNING状态或
  39. // 状态为SHUTDOWN,且 firstTask 为空 且 workQueue 不空
  40. for (;;) {
  41. int wc = workerCountOf(c);
  42. // Worker数量超过容量,直接返回false
  43. if (wc >= CAPACITY || wc >= (core ? corePoolSize : maximumPoolSize))
  44. return false;
  45. // 使用CAS的方式增加worker数量。
  46. // 若增加成功,则直接跳出外层循环进入到第二部分
  47. if (compareAndIncrementWorkerCount(c))
  48. break retry;
  49. c = ctl.get(); // Re-read ctl
  50. // 线程池状态发生变化,对外层循环进行自旋
  51. if (runStateOf(c) != rs)
  52. continue retry;
  53. // else CAS failed due to workerCount change; retry inner loop
  54. }
  55. }
  56. boolean workerStarted = false;
  57. boolean workerAdded = false;
  58. Worker w = null;
  59. try {
  60. w = new Worker(firstTask);
  61. final Thread t = w.thread;
  62. if (t != null) {
  63. final ReentrantLock mainLock = this.mainLock;
  64. // 对 workers 的操作是串行化的
  65. mainLock.lock();
  66. try {
  67. // Recheck while holding lock.
  68. // Back out on ThreadFactory failure or if
  69. // shut down before lock acquired.
  70. // 这儿需要重新检查线程池状态
  71. int rs = runStateOf(ctl.get());
  72. // 虽然在第35行判断ctl的状态了,但是在那之后,ctl可能会发生改变
  73. // 比如被SHUTDOWN,那么此时就不能添加worker
  74. if (rs < SHUTDOWN || (rs == SHUTDOWN && firstTask == null)) {
  75. if (t.isAlive()) // precheck that t is startable
  76. throw new IllegalThreadStateException();
  77. workers.add(w);
  78. int s = workers.size();
  79. if (s > largestPoolSize)
  80. largestPoolSize = s;
  81. workerAdded = true;
  82. }
  83. } finally {
  84. mainLock.unlock();
  85. }
  86. // 启动worker线程
  87. if (workerAdded) {
  88. t.start();
  89. workerStarted = true;
  90. }
  91. }
  92. } finally {
  93. // Worker线程启动失败,说明线程池状态发生了变化(关闭操作被执行),需要进行terminated()
  94. if (!workerStarted)
  95. addWorkerFailed(w);
  96. }
  97. return workerStarted;
  98. }

addWorkerFailed()

  1. private void addWorkerFailed(Worker w) {
  2. final ReentrantLock mainLock = this.mainLock;
  3. mainLock.lock();
  4. try {
  5. if (w != null)
  6. workers.remove(w);
  7. decrementWorkerCount();
  8. tryTerminate();
  9. } finally {
  10. mainLock.unlock();
  11. }
  12. }

Worker

先不分析JDK是如何实现线程池里的线程的,假设一下,如果这个需求让我们实现,会做哪些考虑。首先,线程是死循环的,不断的从任务队列中获取任务进行处理。当线程没有任务时需要停止,但是经过TimeOut时间之后需要给线程 interrupt()。而在JDK的实现中完成这个功能的是类 Worker

  1. /**
  2. * Class Worker mainly maintains interrupt control state for
  3. * threads running tasks, along with other minor bookkeeping.
  4. * This class opportunistically extends AbstractQueuedSynchronizer
  5. * to simplify acquiring and releasing a lock surrounding each
  6. * task execution. This protects against interrupts that are
  7. * intended to wake up a worker thread waiting for a task from
  8. * instead interrupting a task being run. We implement a simple
  9. * non-reentrant mutual exclusion lock rather than use
  10. * ReentrantLock because we do not want worker tasks to be able to
  11. * reacquire the lock when they invoke pool control methods like
  12. * setCorePoolSize. Additionally, to suppress interrupts until
  13. * the thread actually starts running tasks, we initialize lock
  14. * state to a negative value, and clear it upon start (in
  15. * runWorker).
  16. */
  17. private final class Worker
  18. extends AbstractQueuedSynchronizer
  19. implements Runnable {
  20. /** Thread this worker is running in. Null if factory fails. */
  21. final Thread thread;
  22. /** Initial task to run. Possibly null. */
  23. Runnable firstTask;
  24. /** Per-thread task counter */
  25. volatile long completedTasks;
  26. /**
  27. * Creates with given first task and thread from ThreadFactory.
  28. * @param firstTask the first task (null if none)
  29. */
  30. Worker(Runnable firstTask) {
  31. setState(-1); // inhibit interrupts until runWorker
  32. this.firstTask = firstTask;
  33. // 实际上在这,是将自己给封装起来了,以thread运行后,运行的是Workder的run方法
  34. this.thread = getThreadFactory().newThread(this);
  35. }
  36. /** Delegates main run loop to outer runWorker */
  37. public void run() {
  38. runWorker(this);
  39. }
  40. // Lock methods
  41. //
  42. // The value 0 represents the unlocked state.
  43. // The value 1 represents the locked state.
  44. protected boolean isHeldExclusively() {
  45. return getState() != 0;
  46. }
  47. protected boolean tryAcquire(int unused) {
  48. if (compareAndSetState(0, 1)) {
  49. setExclusiveOwnerThread(Thread.currentThread());
  50. return true;
  51. }
  52. return false;
  53. }
  54. protected boolean tryRelease(int unused) {
  55. setExclusiveOwnerThread(null);
  56. setState(0);
  57. return true;
  58. }
  59. public void lock() { acquire(1); }
  60. public boolean tryLock() { return tryAcquire(1); }
  61. public void unlock() { release(1); }
  62. public boolean isLocked() { return isHeldExclusively(); }
  63. void interruptIfStarted() {
  64. Thread t;
  65. if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
  66. try {
  67. t.interrupt();
  68. } catch (SecurityException ignore) {
  69. }
  70. }
  71. }
  72. }

runWorker()

  1. final void runWorker(Worker w) {
  2. Thread wt = Thread.currentThread();
  3. Runnable task = w.firstTask;
  4. w.firstTask = null;
  5. w.unlock(); // allow interrupts
  6. boolean completedAbruptly = true;
  7. try {
  8. // 循环重队列中获取任务
  9. while (task != null || (task = getTask()) != null) {
  10. w.lock();
  11. // If pool is stopping, ensure thread is interrupted;
  12. // if not, ensure thread is not interrupted. This
  13. // requires a recheck in second case to deal with
  14. // shutdownNow race while clearing interrupt
  15. // 如果线程池处于停止状态 且 线程没有被中断,中断当前线程
  16. // 如果线程被中断了(getTask期间),看看线程池是不是停止,如果没有停止,清除中断
  17. if ((runStateAtLeast(ctl.get(), STOP) ||
  18. (Thread.interrupted() && runStateAtLeast(ctl.get(), STOP)))
  19. && !wt.isInterrupted())
  20. wt.interrupt();
  21. try {
  22. beforeExecute(wt, task);
  23. Throwable thrown = null;
  24. try {
  25. // 这一步是串行的
  26. task.run();
  27. } catch (RuntimeException x) {
  28. thrown = x; throw x;
  29. } catch (Error x) {
  30. thrown = x; throw x;
  31. } catch (Throwable x) {
  32. thrown = x; throw new Error(x);
  33. } finally {
  34. afterExecute(task, thrown);
  35. }
  36. } finally {
  37. task = null;
  38. w.completedTasks++;
  39. w.unlock();
  40. }
  41. }
  42. completedAbruptly = false;
  43. } finally {
  44. processWorkerExit(w, completedAbruptly);
  45. }
  46. }

getTask()

  1. private Runnable getTask() {
  2. boolean timedOut = false; // Did the last poll() time out?
  3. for (;;) {
  4. int c = ctl.get();
  5. int rs = runStateOf(c);
  6. // Check if queue empty only if necessary.
  7. // 1.状态是 STOP
  8. // 2.状态是 SHUTDOWN,但 workQueue 是空
  9. //
  10. if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
  11. // 返回空,在runWorker那会阻塞,所以需要在这里将活动Worker降低一个
  12. decrementWorkerCount();
  13. return null;
  14. }
  15. int wc = workerCountOf(c);
  16. // Are workers subject to culling?
  17. // 当前的Worker是否允许时间
  18. boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
  19. // 条件拆解
  20. // 1.wc > maximumPoolSize && wc > 1
  21. // 2.wc > maximumPoolSize && workQueue.isEmpty()
  22. // 3.(timed && timedOut) && wc > 1
  23. // 4.(timed && timedOut) && workQueue.isEmpty()
  24. // 解释
  25. // 1.如果比最大线程数大 且 还有其他正在运行的线程
  26. // 2.如果比最大线程数大 且 工作队列为空
  27. // 3.如果当前线程获取任务超时 且 还有其他正在运行的线程
  28. // 4.如果当前线程获取任务超时 且 工作队列为空
  29. // 结果
  30. // 使当前线程不再工作
  31. if ((wc > maximumPoolSize || (timed && timedOut))
  32. && (wc > 1 || workQueue.isEmpty())) {
  33. if (compareAndDecrementWorkerCount(c))
  34. return null;
  35. continue;
  36. }
  37. // 能够运行到这一步的条件是
  38. // 1.wc <= maxmaximumPoolSize && !(timed && timeOut)
  39. // 2.wc <= 1 && !workQueue.isEmpty()
  40. // 解释
  41. // 1.正在运行的线程个数没有超过最大线程数 且 获取任务没有超时
  42. // 2.没有其他的线程在运行 且 任务队列不空
  43. try {
  44. Runnable r = timed ?
  45. workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
  46. workQueue.take();
  47. if (r != null)
  48. return r;
  49. timedOut = true;
  50. } catch (InterruptedException retry) {
  51. // 如果被中断了,重新计时
  52. timedOut = false;
  53. }
  54. }
  55. }

小结

一个Worker是一个真正运行的线程。循环的从任务队列里面取出Runable来执行。实现了AQS是为了在执行真正任务的时候屏蔽中断,只有在获取任务(getTask())的时候才能响应中断。

ScheduledExecutorService

java.util.concurrent.ScheduledExecutorService 是一个 ExecutorService, 它能够将任务延后执行,或者间隔固定时间多次执行。 任务由一个工作者线程异步执行,而不是由提交任务给 ScheduledExecutorService 的那个线程执行。

  1. public class TestExecutor {
  2. public static void main(String[] args) throws ExecutionException, InterruptedException {
  3. ScheduledExecutorService scheduledExecutorService =
  4. Executors.newScheduledThreadPool(5);
  5. ScheduledFuture scheduledFuture =
  6. scheduledExecutorService.schedule(
  7. new Callable() {
  8. public Object call() throws Exception {
  9. System.out.println("Executed!");
  10. return "Called!";
  11. }
  12. },
  13. 5,
  14. TimeUnit.SECONDS); // 5 秒后执行
  15. scheduledExecutorService.shutdown();
  16. }
  17. }

ScheduledExecutorService 的实现

ScheduledExecutorService 是一个接口,你要用它的话就得使用 java.util.concurrent 包里对它的某个实现类。
ScheduledExecutorService 具有以下实现类:ScheduledThreadPoolExecutor

创建一个 ScheduledExecutorService

如何创建一个 ScheduledExecutorService 取决于你采用的它的实现类。但是你也可以使用 Executors 工厂类
来创建一个 ScheduledExecutorService 实例。比如:

  1. ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);

ScheduledExecutorService 的使用

一旦你创建了一个 ScheduledExecutorService,你可以通过调用它的以下方法:

  • schedule (Callable task, long delay, TimeUnit timeunit)
  1. public class TestExecutor {
  2. public static void main(String[] args) throws Exception {
  3. ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
  4. ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(
  5. new Callable() {
  6. public Object call() throws Exception {
  7. System.out.println("Executed!");
  8. return "Called!";
  9. }
  10. },
  11. 5,
  12. TimeUnit.SECONDS);
  13. System.out.println("result = " + scheduledFuture.get());
  14. scheduledExecutorService.shutdown();
  15. }
  16. }
  • schedule (Runnable task, long delay, TimeUnit timeunit)
  • scheduleAtFixedRate (Runnable, task long initialDelay, long period, TimeUnit timeunit)

这一方法规划一个任务将被定期执行。该任务将会在首个 initialDelay 之后得到执行,然后每个 period 时间之
后重复执行。如果给定任务的执行抛出了异常,该任务将不再执行。如果没有任何异常的话,这个任务将会持续循环执行到ScheduledExecutorService 被关闭。如果一个任务占用了比计划的时间间隔更长的时候,下一次执行将在当前执行结束执行才开始。计划任务在同一时间不会有多个线程同时执行。

  • scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)

除了 period 有不同的解释之外这个方法和 scheduleAtFixedRate() 非常像。scheduleAtFixedRate() 方法中,period 被解释为前一个执行的开始和下一个执行的开始之间的间隔时间。而在本方法中,period 则被解释为前一个执行的结束和下一个执行的结束之间的间隔。因此这个延迟是执行结束之间的间隔,而不是执行开始之间的间隔。