public
static
void
method1() {
BlockingQueue queue =
new
LinkedBlockingQueue();
ThreadPoolExecutor executor =
new
ThreadPoolExecutor(3, 6, 10, TimeUnit.
SECONDS
, queue);
for
(
int
i = 0; i < 20; i++) {
executor.execute(
new
Runnable() {
public
void
run() {
try
{
System.
out
.println(
this
.hashCode()/1000);
for
(
int
j = 0; j < 10; j++) {
System.
out
.println(
this
.hashCode() +
":"
+ j);
Thread.sleep(
this
.hashCode()%2);
}
}
catch
(InterruptedException e) {
e.printStackTrace();
}
System.
out
.println(String. format(
"thread %d finished"
,
this
.hashCode()));
}
});
}
}
|
debug模式下,任務執行完後,顯示的效果以下:
![]()
也就是說,任務已經執行完畢了,可是線程池中的線程並無被回收。可是我在
ThreadPoolExecutor的參數裏面設置了超時時間的,好像沒起做用,緣由以下:
工做線程回收須要知足三個條件:
1) 參數allowCoreThreadTimeOut爲truehtml 2) 該線程在keepAliveTime時間內獲取不到任務,即空閒這麼長時間程序員
3) 當前線程池大小 > 核心線程池大小corePoolSize。
|
public
static
void
method1() {
BlockingQueue queue =
new
LinkedBlockingQueue();
ThreadPoolExecutor executor =
new
ThreadPoolExecutor(3, 6, 1, TimeUnit.
SECONDS
, queue);
executor.allowCoreThreadTimeOut(
true);
for
(
int
i = 0; i < 20; i++) {
executor.execute(
new
Runnable() {
public
void
run() {
try
{
System.
out
.println(
this
.hashCode()/1000);
for
(
int
j = 0; j < 10; j++) {
System.
out
.println(
this
.hashCode() +
":"
+ j);
Thread. sleep(
this
.hashCode()%2);
}
}
catch
(InterruptedException e) {
e.printStackTrace();
}
System.
out
.println(String. format(
"thread %d finished"
,
this
.hashCode()));
}
});
}
}
|
須要注意的是,allowCoreThreadTimeOut 的設置須要在任務執行以前,通常在new一個線程池後設置;在allowCoreThreadTimeOut設置爲true時,ThreadPoolExecutor的keepAliveTime參數必須大於0。 |
public
static
void
method1() {
BlockingQueue queue =
new
LinkedBlockingQueue();
ThreadPoolExecutor executor =
new
ThreadPoolExecutor(3, 6, 1, TimeUnit.
SECONDS
, queue);
for
(
int
i = 0; i < 20; i++) {
executor.execute(
new
Runnable() {
public
void
run() {
try
{
System.
out
.println(
this
.hashCode()/1000);
for
(
int
j = 0; j < 10; j++) {
System.
out
.println(
this
.hashCode() +
":"
+ j);
Thread. sleep(
this
.hashCode()%2);
}
}
catch
(InterruptedException e) {
e.printStackTrace();
}
System.
out
.println(String. format(
"thread %d finished"
,
this
.hashCode()));
}
});
}
executor.shutdown();
}
|
在任務執行完後,調用shutdown方法,將線程池中的空閒線程回收。該方法會使得keepAliveTime參數失效。 |