java.util.concurrent.threadpoolexecutor
是一个executorservice
,可以使用可能的几个池线程来执行每个提交的任务,通常使用executors
工厂方法进行配置。 它还提供了各种实用方法来检查当前线程统计信息并进行控制。
以下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("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.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();
}
}
}
}
执行上面程序,得到以下结果 -
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