以下任何代码片段是否可以保证 pool1 仅在池完成执行后才会启动?
片段 1
ExecutorService pool = Executors.newFixedThreadPool(numberOfThreads);
for (FObject action : list) {
if (action instanceof FObject) {
Runnable run = new ImageProcessRunnable(action);
pool.execute(run);
}
}
pool.shutdown();
if (pool.awaitTermination(10, TimeUnit.SECONDS)) {
pool.shutdownNow();
}
ExecutorService pool1 = Executors.newFixedThreadPool(numberOfThreads);
synchronized (ImageHelper.getFilePaths()) {
for (String file :ImageHelper.getFilePaths()) {
pool1.execute(() -> {
UploadFileAsAppUser.uploadFileAsBoxAppUser(file, boxLocation);
});
}
}
pool1.shutdown();
if (pool1.awaitTermination(10, TimeUnit.SECONDS)) {
pool1.shutdownNow();
}
片段 2
for (FObject action : list) {
if (action instanceof FObject) {
ImageProcessor processor = new ImageProcessor();
}
}
ExecutorService pool1 = Executors.newFixedThreadPool(numberOfThreads);
synchronized (ImageHelper.getFilePaths()) {
for (String file :ImageHelper.getFilePaths()) {
pool1.execute(() -> {
UploadFileAsAppUser.uploadFileAsBoxAppUser(file, boxLocation);
});
}
}
pool1.shutdown();
if (pool1.awaitTermination(10, TimeUnit.SECONDS)) {
pool1.shutdownNow();
}
在片段 1 中,我正在练习并在多个线程中上传图像。在片段 2 中,我正在单线程中处理图像并以多个线程上传它们。
如果要
等待一个或多个任务完成,然后再开始另一个任务,则 CountDownLatch 通常很有用。