📌  相关文章
📜  ThreadPoolExecutor类

📅  最后修改于: 2020-11-15 03:58:48             🧑  作者: Mango


java.util.concurrent.ThreadPoolExecutor是一个ExecutorService,它可以使用可能是多个池线程中的一个来执行每个提交的任务,通常使用Executors工厂方法对其进行配置。它还提供了各种实用程序方法来检查当前线程统计信息并进行控制。

ThreadPoolExecutor方法

Sr.No. Method & Description
1

protected void afterExecute(Runnable r, Throwable t)

Method invoked upon completion of execution of the given Runnable.

2

void allowCoreThreadTimeOut(boolean value)

Sets the policy governing whether core threads may time out and terminate if no tasks arrive within the keep-alive time, being replaced if needed when new tasks arrive.

3

booleanallowsCoreThreadTimeOut()

Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive.

4

booleanawaitTermination(long timeout, TimeUnit unit)

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

5

protected void beforeExecute(Thread t, Runnable r)

Method invoked prior to executing the given Runnable in the given thread.

6

void execute(Runnable command)

Executes the given task sometime in the future.

7

protected void finalize()

Invokes shutdown when this executor is no longer referenced and it has no threads.

8

intgetActiveCount()

Returns the approximate number of threads that are actively executing tasks.

9

long getCompletedTaskCount()

Returns the approximate total number of tasks that have completed execution.

10

intgetCorePoolSize()

Returns the core number of threads.

11

longgetKeepAliveTime(TimeUnit unit)

Returns the thread keep-alive time, which is the amount of time that threads in excess of the core pool size may remain idle before being terminated.

12

intgetLargestPoolSize()

Returns the largest number of threads that have ever simultaneously been in the pool.

13

intgetMaximumPoolSize()

Returns the maximum allowed number of threads.

14

intgetPoolSize()

Returns the current number of threads in the pool.

15

BlockingQueue getQueue()

Returns the task queue used by this executor.

15

RejectedExecutionHandler getRejectedExecutionHandler()

Returns the current handler for unexecutable tasks.

16

long getTaskCount()

Returns the approximate total number of tasks that have ever been scheduled for execution.

17

ThreadFactory getThreadFactory()

Returns the thread factory used to create new threads.

18

booleanisShutdown()

Returns true if this executor has been shut down.

19

booleanisTerminated()

Returns true if all tasks have completed following shut down.

20

booleanisTerminating()

Returns true if this executor is in the process of terminating after shutdown() or shutdownNow() but has not completely terminated.

21

intprestartAllCoreThreads()

Starts all core threads, causing them to idly wait for work.

22

booleanprestartCoreThread()

Starts a core thread, causing it to idly wait for work.

23

void purge()

Tries to remove from the work queue all Future tasks that have been cancelled.

24

booleanremove(Runnable task)

Removes this task from the executor’s internal queue if it is present, thus causing it not to be run if it has not already started.

25

void setCorePoolSize(int corePoolSize)

Sets the core number of threads.

26

void setKeepAliveTime(long time, TimeUnit unit)

Sets the time limit for which threads may remain idle before being terminated.

27

void setMaximumPoolSize(int maximumPoolSize)

Sets the maximum allowed number of threads.

28

void setRejectedExecutionHandler(RejectedExecutionHandler handler)

Sets a new handler for unexecutable tasks.

29

void setThreadFactory(ThreadFactory threadFactory)

Sets the thread factory used to create new threads.

30

void shutdown()

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

31

List shutdownNow()

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

32

protected void terminated()

Method invoked when the Executor has terminated.

33

String toString()

Returns a string identifying this pool, as well as its state, including indications of run state and estimated worker and task counts.

下面的TestThread程序显示了在基于线程的环境中ThreadPoolExecutor接口的用法。

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThread {
    
   public static void main(final String[] arguments) throws InterruptedException {
      ThreadPoolExecutor executor = (ThreadPoolExecutor)Executors.newCachedThreadPool();

      //Stats before tasks execution
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.submit(new Task());
      executor.submit(new Task());

      //Stats after tasks execution
      System.out.println("Core threads: " + executor.getCorePoolSize());
      System.out.println("Largest executions: "
         + executor.getLargestPoolSize());
      System.out.println("Maximum allowed threads: "
         + executor.getMaximumPoolSize());
      System.out.println("Current threads in pool: "
         + executor.getPoolSize());
      System.out.println("Currently executing threads: "
         + executor.getActiveCount());
      System.out.println("Total number of threads(ever scheduled): "
         + executor.getTaskCount());

      executor.shutdown();
   }  

   static class Task implements Runnable {

      public void run() {

         try {
            Long duration = (long) (Math.random() * 5);
            System.out.println("Running Task! Thread Name: " +
               Thread.currentThread().getName());
            TimeUnit.SECONDS.sleep(duration);
            System.out.println("Task Completed! Thread Name: " +
               Thread.currentThread().getName());
         } catch (InterruptedException e) {
            e.printStackTrace();
         }
      }
   }
}

这将产生以下结果。

输出

Largest executions: 0
Maximum allowed threads: 2147483647
Current threads in pool: 0
Currently executing threads: 0
Total number of threads(ever scheduled): 0
Core threads: 0
Largest executions: 2
Maximum allowed threads: 2147483647
Current threads in pool: 2
Currently executing threads: 2
Total number of threads(ever scheduled): 2
Running Task! Thread Name: pool-1-thread-2
Running Task! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-1
Task Completed! Thread Name: pool-1-thread-2