我正在查看ThreadPoolExecutor
类,我发现它允许指定最大池大小和核心池大小。什么是ThreadPoolExecutor的核心线程?
我明白了,一点点,什么时候改变基于此答案的核心和最大池大小:When is specifying separate core and maximum pool sizes in ThreadPoolExecutor a good idea?
不过,我想知道这些是什么“芯线”。我总是得到0,当我使用这里ThreadPoolExecutor
SSCCE的getCorePoolSize()
方法:
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
}
}
好的,如果在“缓存线程池”中,我改变了核心线程的数量,然后类似于“固定线程池”,这些人将永远在那里。但是,未使用超过一分钟的线程将被丢弃。净结果是结合了缓存和固定线程池的好处。对 ? –
您最终创建了一个只有少量线程的池,这些线程始终处于待机状态,并根据需要创建其他线程。空闲线程不会占用内存,因为它们所占用的资源将被释放。 –