For task processing through the thread pool, sometimes we need to know the execution status of the tasks in the thread pool.
Obtain information such as the number of threads, the number of queued tasks, and the number of completed threads in real time through the related APIs of ThreadPoolExecutor.
example
private
static
ExecutorService
es =
new
ThreadPoolExecutor
(
50
,
100
,
0L
,
TimeUnit
.MILLISECONDS,
new
LinkedBlockingQueue
<
Runnable
>(
100000
));
public
static
void
main(
String
[] args)
throws
Exception
{
for
(
int
i =
0
; i <
100000
; i++) {
es.execute(() -> {
System
.
out
.
print
(
1
);
try
{
Thread
.sleep(
1000
);
}
catch
(
InterruptedException
e) {
e.printStackTrace();
}
});
}
ThreadPoolExecutor
tpe = ((
ThreadPoolExecutor
) es);
while
(
true
) {
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);
Thread
.sleep(
3000
);
}
}
For example, we get execution status information every 3 seconds, and there are a total of 50 worker threads.
First output:
当前排队线程数:
99950
当前活动线程数:
50
执行完成线程数:
0
总线程数(排队线程数 + 活动线程数 + 执行完成线程数):
100000
Second output:
当前排队线程数:
99800
当前活动线程数:
50
执行完成线程数:
150
总线程数(排队线程数 + 活动线程数 + 执行完成线程数):
100000
It shows that the changing number of threads and thread tasks can be obtained through the API.