我看到這個問題被問了很多次。很抱歉再次問這個問題。我有個奇怪的問題。
我有一個通過ExecutorService作為單獨的可運行任務(wù)提交數(shù)千個作業(yè)的職務(wù)。這是在一個簡單的for循環(huán)中完成的。在for循環(huán)的末尾,我調(diào)用service.候機(),然后是一個等待高潮。
由于要提交的線程數(shù)量很大,所以線程一直掛起,直到所有任務(wù)都提交為止。
有任何方法,這些線程可以優(yōu)雅地終止,一旦它的執(zhí)行完成?
您可以創(chuàng)建一個新的ThreadPoolExecuto不打電話java.util.concurrent.Executors :
int corePoolSize = 0;
int maximumPoolSize = 64;
int keepAliveTime = 5000;
ExecutorService executorService =
new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime,
TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
在javadoc中:“如果池當(dāng)前有多個corePoolSize線程,那么如果多余的線程已經(jīng)空閑超過了持有AliveTime,那么多余的線程將被終止”
編輯:
下面是一個很小的例子,如果您在Eclipse調(diào)試環(huán)境中運行這個示例,您應(yīng)該可以看到線程的來來去去:
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ExecutorTest {
public static void main(String[] args) {
ExecutorService executorService = new ThreadPoolExecutor(0, 64, 1000,
TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
for (int i = 0; i <= 500; i ++) {
try {
Thread.sleep(new Random().nextInt(200));
} catch (InterruptedException e) {
}
executorService.submit(new TestTask());
}
}
public static class TestTask implements Runnable {
public void run() {
try {
Thread.sleep(new Random().nextInt(1500));
} catch (InterruptedException e) {
}
}
}
}