Thread Executor

Keywords: Java

Executor is brought in by java 5. This mechanism is called execution framework. It focuses on executor interface and its subclass interface ExecutorService, as well as the implementation of these two interfaces
Expanded by ThreadPoolExecutor

Executors creating executors

ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();


  executor.getPoolSize();           //Returns the size of the thread pool

  executor.getActiveCount();        //Returns the number of threads that are executing the task.

  executor.getCompletedTaskCount(); //Returns the number of completed task tasks.

  executor.getLargestPoolSize();    //Returns the maximum number of threads that were in the thread pool at the same time.

  Close now.
  1.No longer executing the waiting thread
  2.Returns a list of threads waiting to execute
  3.The running thread will continue to run

    If the shutdownNow() or shutdown() method is called and the executor completes the shutdown process, true is returned

  If the shutdown() method is called, true is returned


Single thread executor

  executor = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();


Fixed size actuator 2


 executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);

Run multiple tasks and process the first result

 invokeAny Method to receive multiple threads and return the execution result of the first completed task without throwing an exception


Run multiple tasks and process all results

 //Send a thread list to the executor and wait for all tasks in the list to finish.


Delay task execution

 ScheduledThreadPoolExecutor scheduledThreadPoolExecutor =
  (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); //The size of the thread pool is 5
scheduledThreadPoolExecutor.schedule(() -> { }, 1, TimeUnit.SECONDS);  //The task will be executed one second later.

If you want to execute at a certain point in time, you need to calculate the difference between the current time and the expected time


Periodic execution of tasks



1 means the task will be executed in 1 second
2 means that the interval between two tasks is 2 seconds
Note: Although the interval between the two tasks is 2 seconds, if the execution time of the previous thread is greater than 2 seconds. It is possible that two or more threads coexist




2 indicates the interval from the end time of the previous task to the start time of the next task.
Note that in this case. There will be no coexistence of the previous task and the next task

Posted by krellen on Sat, 11 Jan 2020 08:31:11 -0800