简体   繁体   中英

Execute Thread 2 only after Thread 1 finishes

Would any of the following codes snippets give a guarantee that pool1 will start only after the pool finished its execution?

Snippet 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();
    }

Snippet 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();
    }

In snippet 1, I am prcessing as well as uploading images in multiple threads. In snippet 2, I am processing images in single thread and uploading them in multiple threds.

如果要在启动另一个任务之前等待一个或多个任务完成,则CountDownLatch通常很有用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM