仅在线程1完成后才执行线程2

时间:2019-04-07 04:05:16

标签: java multithreading executorservice

以下任何代码片段都可以保证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中,我正在单线程中处理图像,并以多个线程上传它们。

1 个答案:

答案 0 :(得分:0)

如果您想等待一个或多个任务完成然后再开始另一个任务,CountDownLatch通常很有用。