//<!-- 需要依賴 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();
}
}
};
}
}