簡體   English   中英

用循環遍歷一個線程並處理多個結果

[英]Iterate through a thread with loop and process multiple results

我正在嘗試使用線程使我的程序並行運行某些部分並且正在掙扎。

目標是通過ImageProcessor().processLink urlList函數處理鏈接列表urlList 我有兩個問題要解決:

  1. 我如何循環它以便它使用池中的 N 個線程,在這種情況下是 10 個? 也就是說,我想一次處理 10 個鏈接。
  2. 上面的處理函數返回一個File ,我需要將它添加到一個數組fileList 當涉及到多線程時,我將如何處理?

這是我到目前為止所得到的:

    ArrayList<String> urlList = new ArrayList<>(Arrays.asList(arr.split("\\r?\\n"))) ;
    ArrayList<File> fileList = new ArrayList<>();
    ExecutorService executor = Executors.newFixedThreadPool(10);

    //process the requested files
    for (int i = 0; i < urlList.size(); i++){
        Future<File> value = executor.submit(new Callable<File>() {
            @Override
            public File call(int i) throws IOException {
                return new ImageProcessor().processLink(urlList.get(i));
            }
        });

        try {
            fileList.add(value.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

得到它與以下工作:

    ArrayList<String> urlList = new ArrayList<>(Arrays.asList(arr.split("\\r?\\n"))) ;
    ArrayList<File> fileList = new ArrayList<>();

    ExecutorService executor = Executors.newFixedThreadPool(THREAD_SIZE);
    List<Future<File>> futures = new ArrayList<>();

    for (int i = 0; i < urlList.size(); i++) {
        ImageProcessor proc = new ImageProcessor(urlList.get(i));
        final Future<File> future = executor.submit(proc);
        futures.add(future);
    }

    try {
        executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < futures.size(); i++)
    {
        Future<File> result = futures.get(i);
        try {
            fileList.add(result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    executor.shutdown();
    while (!executor.isTerminated()) { }
    System.out.println("Finished all threads");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM