1. 1 public void execute(Runnable command) {
  2. 2 if (command == null)
  3. 3 throw new NullPointerException();
  4. 4 // If the number of threads is less than the base number of threads, a thread is created and the current task is executed
  5. 5 if (poolSize >= corePoolSize || ! addIfUnderCorePoolSize(command)) {
  6. 6 // If the number of threads is greater than or equal to the basic number of threads or thread creation fails, the current task is put to the work queue.
  7. 7 if (runState == RUNNING && workQueue.offer(command)) {
  8. 8 if (runState ! = RUNNING || poolSize == 0) {
  9. 9 ensureQueuedTaskHandled(command);
  10. 10}
  11. 11 // If the thread pool is not running or the task cannot be queued, and the current number of threads is less than the maximum number of threads allowed, a thread is created to execute the task
  12. 12 } else if (! addIfUnderCorePoolSize(command)) {
  13. 13 / / throw RejectedExecutionException anomalies
  14. 14 reject(command); // is shutdown or saturated
  15. 15
  16. 16}
  17. 17}
  18. 18}
  1. 1 public void run() {
  2. 2
  3. 3 try {
  4. 4
  5. 5 Runnable task = firstTask;
  6. 6
  7. 7 firstTask = null;
  8. 8
  9. 9 while (task ! = null || (task = getTask()) ! = null) {
  10. 10
  11. 11 runTask(task);
  12. 12
  13. 13 task = null;
  14. 14
  15. 15}
  16. 16
  17. 17 } finally {
  18. 18
  19. 19 workerDone(this);
  20. 20
  21. 21}
  22. 22
  23. 23}
1 2 new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, milliseconds,runnableTaskQueue, threadFactory,handler);
  • CorePoolSize (base size of the thread pool) : When a task is submitted to the thread pool, the thread pool creates a thread to execute the task, even if other free base threads are able to execute new tasks, until the number of tasks that need to be executed exceeds the base size of the thread pool. If the thread pool’s prestartAllCoreThreads method is called, the pool creates and starts all base threads ahead of time.
  • RunnableTaskQueue: A blocking queue that holds tasks waiting to be executed. You can choose from the following blocking queues.
  1. ArrayBlockingQueue: ArrayBlockingQueue is a bounded blocking queue based on an array structure that sorts elements in FIFO (first-in, first-out) order.
  2. LinkedBlockingQueue: A blocking queue based on a linked list structure that sorts elements in FIFO (first in, first out) and typically has a higher throughput than ArrayBlockingQueue. Static factory methods Executors. NewFixedThreadPool () using the queue.
  3. SynchronousQueue: A blocking queue that does not store elements. Each insert operation must wait until another thread calls to remove operation, otherwise the insert has been in the blocking state, the throughput is usually more than LinkedBlockingQueue, static factory methods Executors. NewCachedThreadPool using the queue.
  4. PriorityBlockingQueue: An infinite blocking queue with a priority.
  • MaximumPoolSize: The maximum number of threads allowed to be created in a thread pool. If the queue is full and the number of threads created is less than the maximum, the thread pool creates a new thread to execute the task. Note that this parameter has no effect if the unbounded task queue is used.
  • ThreadFactory: Used to set up a factory for creating threads. You can use the ThreadFactory to give each thread a meaningful name, which is very helpful for debugging and locating problems.

  1. CallerRunsPolicy: Run the task only in the caller’s thread.
  2. DiscardOldestPolicy: Discards the most recent task in the queue and executes the current task.
  3. DiscardPolicy: Do not process, discard.
  4. You can also customize the RejectedExecutionHandler interface based on application scenarios. Such as logging or persisting tasks that cannot be processed.
  • KeepAliveTime: The amount of time that a worker thread in a thread pool stays alive after it is idle. Therefore, if there are many tasks and the execution time of each task is short, you can increase the duration to improve thread utilization.
  • TimeUnit (a unit of hold time for thread activity) : The options are in DAYS, HOURS, MINUTES, MILLISECONDS, MICROSECONDS and NANOSECONDS.
  1. 1 threadsPool.execute(new Runnable() {
  2. 2 @Override
  3. 3
  4. 4 public void run() {
  5. 5
  6. 6 // TODO Auto-generated method stub
  7. 7
  8. 8}
  9. 9
  10. 10});
  1. try {
  2. Object s = future.get();
  3. } catch (InterruptedException e) {
  4. // Handle the interrupt exception
  5. } catch (ExecutionException e) {
  6. // Handle the exception that tasks cannot be executed
  7. } finally {
  8. // Close the thread pool
  9. executor.shutdown();
  10. }
  1. Nature of tasks: CPU intensive tasks, IO intensive tasks and hybrid tasks.
  2. Task priority: high, medium and low.
  3. Task execution time: long, medium and short.
  4. Task dependencies: Whether they depend on other system resources, such as database connections.
  • TaskCount: Indicates the number of tasks that need to be executed by the thread pool.
  • CompletedTaskCount: The number of tasks completed by the thread pool during a run. Less than or equal to taskCount.
  • LargestPoolSize: maximum number of threads ever created by the thread pool. This data lets you know if the thread pool is full. If equal to the maximum size of the thread pool, it indicates that the thread pool was once full.
  • GetPoolSize: specifies the number of threads in the thread pool. Threads in the pool will not destroy themselves if the pool is not destroyed, so the size will only increase.
  • GetActiveCount: Gets the number of active threads.
  1. <b>protected</b> <b>void</b> beforeExecute(Thread t, Runnable r) { }