ThreadPoolExecutor中的核心线程是什么?

Lit*_*ild 3 java multithreading threadpoolexecutor

我正在查看ThreadPoolExecutor该类,我发现它允许指定最大池大小和核心池大小.

我有点了解何时根据这里的答案更改核心和最大池大小:何时在ThreadPoolExecutor中指定单独的核心和最大池大小是一个好主意?

但是,我想知道这些"核心线程"是什么.当我使用a的getCorePoolSize()方法时,我总是得到0ThreadPoolExecutor

SSCCE在这里:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

public class PoolSize {
    public static void main(String[] args) {
        // Create a cached thread pool
        ExecutorService cachedPool = Executors.newCachedThreadPool();
        // Cast the object to its class type
        ThreadPoolExecutor pool = (ThreadPoolExecutor) cachedPool;

        // Create a Callable object of anonymous class
        Callable<String> aCallable = new Callable<String>(){
            String result = "Callable done !";
            @Override
            public String call() throws Exception {
                // Print a value
                System.out.println("Callable at work !");
                // Sleep for 5 sec
                Thread.sleep(0);
                return result;
            }
        };

        // Create a Runnable object of anonymous class
        Runnable aRunnable = new Runnable(){
            @Override
            public void run() {
                try {
                    // Print a value
                    System.out.println("Runnable at work !");
                    // Sleep for 5 sec
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        // Submit the two tasks for execution
        Future<String> callableFuture = cachedPool.submit(aCallable);
        Future<?> runnableFuture = cachedPool.submit(aRunnable);

        System.out.println("Core threads: " + pool.getCorePoolSize());
        System.out.println("Largest number of simultaneous executions: " 
                                            + pool.getLargestPoolSize());
        System.out.println("Maximum number of  allowed threads: " 
                                            + pool.getMaximumPoolSize());
        System.out.println("Current threads in the pool: " 
                                            + pool.getPoolSize());
        System.out.println("Currently executing threads: " 
                                            + pool.getTaskCount());

        pool.shutdown(); // shut down

    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 5

核心线程是最小的,它总是在你想要传递任务的情况下运行.默认情况下,缓存池具有0您可能期望的核心.

对于固定线程池,核心和最大值是相同的,即无论你设置固定大小.