An overview,

  • Tencent interview time was asked, sum up

Second, the classification of

1, CachedThreadPool

  • It’s a thread pool that can expand indefinitely;

  • It is more suitable for processing tasks with relatively small execution time;

  • CorePoolSize is 0 and maximumPoolSize is infinite, meaning the number of threads can be infinite.

  • KeepAliveTime is 60 seconds, meaning that the thread will be killed if the idle time exceeds 60 seconds.

  • SynchronousQueue holds waiting tasks. The blocking queue has no storage space. This means that whenever a request arrives, a worker thread must be found to process it, and a new thread must be created if no thread is currently idle.

public static ExecutorService newCachedThreadPool(a){ 
    return new ThreadPoolExecutor(
    0.// Number of core threads
    Integer.MAX_VALUE, // Maximum number of threads
    60L,
    TimeUnit.MILLISECONDS,
    new SynchronousQueue<Runnable>()); 
 }

Copy the code

1, SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor(a){
    return new ThreadPoolExecutor(
    1.1.0L,
    TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>());
}
Copy the code
  • It creates only one worker thread to process the task;
  • The blocking queue used is LinkedBlockingQueue;

3, FixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads){
    return new ThreadPoolExecutor(
    nThreads,
    nThreads,
    0L,
    TimeUnit.MILLISECONDS,
    new LinkedBlockingQueue<Runnable>());
    }
Copy the code
  • It’s a fixed-size thread pool;

  • CorePoolSize and maximunPoolSize both specify the number of threads specified by the user.

  • KeepAliveTime is 0, which means that once there are extra idle threads, they are stopped immediately. But keepAliveTime is invalid;

  • Because a blocking queue is an unbounded queue, it is never possible to reject a task;

  • Because of the unbounded queue, the actual number of threads will always remain at nThreads, so maximumPoolSize and keepAliveTime will not be valid.

4, ScheduledThreadPool

  • It is used to handle delayed or timed tasks.

  • ScheduledFuture<? > schedule(Runnable command, long delay, TimeUnit unit)

    • Create and perform a one-time operation that is enabled after a given delay.
  • ScheduledFuture<? > scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

    • Create and execute a periodic operation that is enabled for the first time after a given initial delay, with subsequent operations having a given period; Which is going to be ininitialDelayAfter the start of execution, and then ininitialDelay+periodAfter the execution, then ininitialDelay + 2 * periodAfter execution, and so on.
  • ScheduledFuture<? > scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)

    • Create and execute a periodic operation that is first enabled after a given initial delay, followed by a given delay between the end of each execution and the start of the next.
  • The difference between

    • The execution period of the scheduleAtFixedRate method is fixed. That is, the execution time of the previous task is used as the starting point and the subsequent period is used to schedule the next task.

    • The scheduleWithFixedDelay method uses the end time of the previous task as the starting point and the subsequent period to schedule the next task.

(1) Parameters

public ScheduledThreadPoolExecutor(int corePoolSize,
                                   ThreadFactory threadFactory,
                                   RejectedExecutionHandler handler) {
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue(), threadFactory, handler);
}
Copy the code
  • ScheduledThreadPoolExecutor support at most three parameters: the core number of threads, thread factory, refused to strategy.

  • The DelayedWorkQueue, which is a small root heap, is unbounded, so the rejection policy and the maximum number of threads are useless

(2) General execution process

  • Check whether the current task is a periodic task. If periodic tasks cannot be executed in the current running status of the thread pool, cancel the task execution. Otherwise, go to Step 2.

  • If the current task is not a periodic task, call the Run method of FutureTask to execute the task, set the execution result, and return directly. Otherwise, perform Step 3.

  • If the current task is a periodic task, call the runAndReset method of the FutureTask class to execute the task without setting the execution result and return directly. Otherwise, go to Step 4.

  • If the task is successfully executed, set the time for executing the task next time and set the task to repeat execution.

If the task fails, the periodic task will not be executed. Second, if the scheduleAtFixedRate (the task start time as the period) is too long, The next task starts only after the current task has been executed. The next task starts immediately because it has timed out.

(3) Summary

  1. Rate is calculated from the start execution time of the previous task. Delay is calculated from the end time of the previous task.

  2. If the time of the task itself exceeds the interval, then the interval time of the two modes will be inconsistent

  3. Tasks are sorted through the compareTo method of ScheduledFutureTask. The rule is to compare the execution time first, and then compare the joining time if the time is the same.

  4. If an exception occurs during the execution of the task, it will not be repeated. Because ScheduledFutureTask’s run method doesn’t do catch.

reference

  • www.zhihu.com/question/23…
  • Blog.csdn.net/org_hjh/art…