//<!-- 需要依赖 pool 对象池 -->
//<dependency>
//<groupId>org.apache.commons</groupId>
//<artifactId>commons-pool2</artifactId>
//</dependency>
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 线程池状态查看
*/
public class TestThread {
private static ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(10, new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build());
public static void main(String[] args) {
executor.schedule(newTask("aaa"), 10, TimeUnit.MILLISECONDS);
executor.schedule(newTask("bbb"), 10, TimeUnit.MILLISECONDS);
executor.schedule(newTask("ccc"), 10, TimeUnit.MILLISECONDS);
executor.schedule(newTask("一秒"), 1000, TimeUnit.MILLISECONDS);
executor.schedule(newTask("5秒"), 5000, TimeUnit.MILLISECONDS);
executor.schedule(badTask(), 10, TimeUnit.MILLISECONDS);
while (getPoolInfo((ThreadPoolExecutor) executor) > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static int getPoolInfo(ThreadPoolExecutor tpe) {
System.out.println();
int queueSize = tpe.getQueue().size();
System.out.println("当前排队线程数:" + queueSize);
int activeCount = tpe.getActiveCount();
System.out.println("当前活动线程数:" + activeCount);
long completedTaskCount = tpe.getCompletedTaskCount();
System.out.println("执行完成线程数:" + completedTaskCount);
long taskCount = tpe.getTaskCount();
System.out.println("总线程数:" + taskCount);
//线程池中当前线程的数量,为0时意味着没有任何线程,线程池会终止,此值不会超过MaximumPoolSize
System.out.println("当前线程的数量:" + tpe.getPoolSize());
//线程池的初始线程数量(当没有任务提交,或提交任务数小于此值值,实际并不会产生那么多线程数)
System.out.println("线程池的初始线程数量:" + tpe.getCorePoolSize());
//线程池可允许最大的线程数
System.out.println("线程池可允许最大的线程数" + tpe.getMaximumPoolSize());
tpe.getLargestPoolSize();
return queueSize;
}
private static TimerTask newTask(String str) {
return new TimerTask() {
@Override
public void run() {
System.err.println("线程:" + Thread.currentThread().getName() + " = " + str);
}
};
}
private static TimerTask badTask() {
return new TimerTask() {
@Override
public void run() {
System.err.println("坏的线程:" + Thread.currentThread().getName());
//对于异常一定要捕获,否则没有任何提示
try {
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
}