Vic*_* P. 5 java multithreading executorservice
我正在寻找一种在java中执行批量任务的方法.我的想法是ExecutorService基于一个线程池,它允许我Callable从一个main线程中传播一组不同的线程.此类应提供waitForCompletion方法,该方法将使main线程处于休眠状态,直到执行所有任务.然后main应该唤醒线程,它将执行一些操作并重新提交一组任务.
这个过程将重复多次,所以我想使用,ExecutorService.shutdown因为这需要创建多个实例ExecutorService.
目前我使用a AtomicInteger和Lock/ 来以下列方式实现它Condition:
public class BatchThreadPoolExecutor extends ThreadPoolExecutor {
private final AtomicInteger mActiveCount;
private final Lock mLock;
private final Condition mCondition;
public <C extends Callable<V>, V> Map<C, Future<V>> submitBatch(Collection<C> batch){
...
for(C task : batch){
submit(task);
mActiveCount.incrementAndGet();
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
mLock.lock();
if (mActiveCount.decrementAndGet() == 0) {
mCondition.signalAll();
}
mLock.unlock();
}
public void awaitBatchCompletion() throws InterruptedException {
...
// Lock and wait until there is no active task
mLock.lock();
while (mActiveCount.get() > 0) {
try {
mCondition.await();
} catch (InterruptedException e) {
mLock.unlock();
throw e;
}
}
mLock.unlock();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我不一定会立即提交批次中的所有任务,因此CountDownLatch似乎不是一种选择.
这是一种有效的方法吗?是否有更有效/更优雅的方式来实现它?
谢谢
| 归档时间: |
|
| 查看次数: |
8815 次 |
| 最近记录: |