首页 > 解决方案 > 将元素添加到多个线程中的列表时被跳过

问题描述

我正在处理一些图像并将它们复制到多个线程中的某个位置。作为处理的一部分,我还将它们添加到列表中。

列表(我在其中添加图像路径)缺少很多元素。我处理了大约 2000 张图像,列表中只有 3 张。

以下是我的代码的一些相关片段:

ImageHelper.java

public class ImageHelper {

    private static List<String> filePaths = Collections.synchronizedList(new ArrayList<String>());

    public synchronized static List<String> getFilePaths(){
        return filePaths;
    }
}

ImageProcessRunnable.Java

public class ImageProcessRunnable implements Runnable {

    FObject action;
    ImageHelper imageHelper = new ImageHelper();

    public ImageProcessRunnable(FObject action) throws IOException {
        this.action = action;
    }

    public void run() {
        try {   
                    String filePath = imageProcessor.processImage(file, materialNumberImgName,
                            ImageHelper.getTempLocation(), ImageHelper.getBoxLocation(), idA2A2, logReport);
                    // I do get all the file paths in the above line from image processor.
                    ImageHelper.getFilePaths().add(filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

图像服务.java

public class ImageService {

List<FObject> list = new Vector<FObject>(results);

public static void loadImages() throws IOException {
        try {           
            SessionContext session = SessionContext.getContext(); 
            ExecutorService pool = Executors.newFixedThreadPool(numberOfThreads);

            for (FObject action : list) {
                if (action instanceof FObject) {    
                    Runnable run = new ImageProcessRunnable(action);
                    SessionThread th=new SessionThread(run, session);
                    pool.execute(th);
                }
                System.out.println("List Size is: "+ImageHelper.getFilePaths().size());
            }
            pool.shutdown();
            if (pool.awaitTermination(2, TimeUnit.SECONDS)) {
                pool.shutdownNow();
            }
        }
    }
}

该代码正在处理所有图像并将其复制到驱动器,但它只是没有将所有图像都添加到 filePaths 列表中。

标签: javamultithreadingrunnableexecutorservice

解决方案


推荐阅读