一種方法是使用一個ThreadPoolExecutor,它會在沒有空閒線程時阻塞。
ThreadPoolExecutor executor = new ThreadPoolExecutor(MAX_REQUESTS, MAX_REQUESTS, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
executor.getQueue().offer(r, Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
for(int i=0;i<LOTS_OF_REQUESTS;i++) {
final int finalI = i;
executor.submit(new Runnable() {
@Override
public void run() {
request(finalI);
}
});
}
另一種方法是讓這些任務生成自己的請求。這樣,每次線程同時釋放時都會生成一個新的請求。
ExecutorService executor = Executors.newFixedThreadPool(MAX_REQUESTS);
final AtomicInteger counter = new AtomicInteger();
for (int i = 0; i < MAX_REQUESTS; i++) {
executor.submit(new Runnable() {
@Override
public void run() {
int i;
while ((i = counter.getAndIncrement()) < LOTS_OF_REQUESTS)
request(i);
}
});
}
您是否在嘗試允許numRequestsProcessing關閉時添加睡眠?所以你不交換服務?一個固定的線程池會給你(或多或少)或通過等待/ notifiy /條件進行線程間合作。 – Toby