通过调用executors
类的静态newcachedthreadpool()
方法可以获得缓存的线程池。
语法
executorservice executor = executors.newcachedthreadpool();
其中,
newcachedthreadpool()
方法创建一个具有可扩展线程池的执行器。以下testthread
程序在线程环境中显示了newcachedthreadpool()
方法的用法。
import java.util.concurrent.executorservice;
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 {
executorservice executor = executors.newcachedthreadpool();
// cast the object to its class type
threadpoolexecutor pool = (threadpoolexecutor) executor;
//stats before tasks execution
system.out.println("core threads: " + pool.getcorepoolsize());
system.out.println("largest executions: "
+ pool.getlargestpoolsize());
system.out.println("maximum allowed threads: "
+ pool.getmaximumpoolsize());
system.out.println("current threads in pool: "
+ pool.getpoolsize());
system.out.println("currently executing threads: "
+ pool.getactivecount());
system.out.println("total number of threads(ever scheduled): "
+ pool.gettaskcount());
executor.submit(new task());
executor.submit(new task());
//stats after tasks execution
system.out.println("core threads: " + pool.getcorepoolsize());
system.out.println("largest executions: "
+ pool.getlargestpoolsize());
system.out.println("maximum allowed threads: "
+ pool.getmaximumpoolsize());
system.out.println("current threads in pool: "
+ pool.getpoolsize());
system.out.println("currently executing threads: "
+ pool.getactivecount());
system.out.println("total number of threads(ever scheduled): "
+ pool.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();
}
}
}
}
这将产生以下结果 -
core threads: 0
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-1
running task! thread name: pool-1-thread-2
task completed! thread name: pool-1-thread-2
task completed! thread name: pool-1-thread-1