我有一個寬度爲10的固定線程池ExecutorService
和一個100 Callable
的列表,每個等待20秒並記錄它們的中斷。Java ExecutorService invokeAll()中斷
我在單獨的線程中調用了該列表上的invokeAll
,並且幾乎立即中斷了此線程。 ExecutorService
執行按預期中斷,但由Callable
s記錄的實際中斷數遠遠超過預期的10-20-40。爲什麼這樣,如果ExecutorService
可以同時執行不超過10個線程?
全部源:(您可能需要更多的,一旦由於併發運行)
@Test
public void interrupt3() throws Exception{
int callableNum = 100;
int executorThreadNum = 10;
final AtomicInteger interruptCounter = new AtomicInteger(0);
final ExecutorService executorService = Executors.newFixedThreadPool(executorThreadNum);
final List <Callable <Object>> executeds = new ArrayList <Callable <Object>>();
for (int i = 0; i < callableNum; ++i) {
executeds.add(new Waiter(interruptCounter));
}
Thread watcher = new Thread(new Runnable() {
@Override
public void run(){
try {
executorService.invokeAll(executeds);
} catch(InterruptedException ex) {
// NOOP
}
}
});
watcher.start();
Thread.sleep(200);
watcher.interrupt();
Thread.sleep(200);
assertEquals(10, interruptCounter.get());
}
// This class just waits for 20 seconds, recording it's interrupts
private class Waiter implements Callable <Object> {
private AtomicInteger interruptCounter;
public Waiter(AtomicInteger interruptCounter){
this.interruptCounter = interruptCounter;
}
@Override
public Object call() throws Exception{
try {
Thread.sleep(20000);
} catch(InterruptedException ex) {
interruptCounter.getAndIncrement();
}
return null;
}
}
使用的WinXP 32位,甲骨文JRE 1.6.0_27和JUnit4
嗯......將它轉換成一個程序,主要方法,我一直(在Windows Java 7中)得到10 ... –
做同樣的,有37(1.6.0_27中,Windows XP)。沒有Java 7測試,有人可以確認嗎? –
我會努力工作。也許這是一個Java 6的bug ... –