我正在查看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
}
}
好的,如果在「緩存線程池」中,我改變了核心線程的數量,然後類似於「固定線程池」,這些人將永遠在那裏。但是,未使用超過一分鐘的線程將被丟棄。淨結果是結合了緩存和固定線程池的好處。對 ? –
您最終創建了一個只有少量線程的池,這些線程始終處於待機狀態,並根據需要創建其他線程。空閒線程不會佔用內存,因爲它們所佔用的資源將被釋放。 –