我的threadPool中有多个线程在运行。每个线程读取一个大文件,并从列表中的该文件返回数据。

代码如下:

class Writer{


   ArrayList finalListWhereDataWillBeWritten = new Array<Integer>()
   for(query q : allQueries){ //all the read queries to read file

      threadPool.submit(new GetDataFromFile(fileName,filePath));

   }//all the read queries have been submitted.

}

现在我知道代码的以下部分将出现在代码中的某些位置,但我不知道将其放置在何处。
因为如果我只是将它放在submit()之后的for循环中,则不会添加它,因为每个文件都非常大,可能尚未完成其处理。
synchronized(finalListWhereDataWillBeWritten){

  //process the data obtained from single file and add it to target list
      finalListWhereDataWillBeWritten.addAll(dataFromSingleThread);

}

所以任何人都可以告诉我,我应该在哪里放置这段代码,以及需要确保确保不要发生“关键部分问题”的其他事项。
class GetDataFromFile implements Runnable<List<Integer>>{

   private String fileName;
   private String filePath;

   public List<Integer> run(){
       //code for streaming the file fileName
       return dataObtainedFromThisFile;
   }

}

考虑到我只是从线程中并行读取文件中的数据并将它们放置在共享列表中,我是否需要在代码中使用wait()/notifyAll()方法

最佳答案

更新请考虑Marko提供的答案,这要好得多

如果要确保在处理列表之前所有线程都已完成,请执行以下操作:

import java.util.List;
import java.util.Vector;

public class ThreadWork {

  public static void main(String[] args) {

    int count = 5;
    Thread[] threads = new ListThread[count];
    List<String> masterList = new Vector<String>();

    for(int index = 0; index < count; index++) {
      threads[index] = new ListThread(masterList, "Thread " + (index + 1));
      threads[index].start();
    }
    while(isOperationRunning(threads)) {
      // do nothing
    }

    System.out.println("Done!! Print Your List ...");

    for(String item : masterList){
      System.out.println("[" + item + "]");
    }
  }

  private static boolean isOperationRunning(Thread[] threads) {
    boolean running = false;

    for(Thread thread : threads) {
      if(thread.isAlive()) {
        running = true;
        break;
      }
    }
    return running;
  }
}

class ListThread extends Thread {
  private static String items[] = { "A", "B", "C", "D"};
  private List<String> list;
  private String name;

  public ListThread(List<String> masterList, String threadName) {
    list = masterList;
    name = threadName;
  }

  public void run() {
    for(int i = 0; i < items.length;++i) {
      randomWait();
      String data = "Thread [" + name + "][" + items[i] + "]";
      System.out.println( data );
      list.add( data );
    }
  }

  private void randomWait() {
    try {
      Thread.currentThread();
      Thread.sleep((long)(3000 * Math.random()));
    }
    catch (InterruptedException x) {}
  }
}

关于java - 线程池中的多个线程在同一列表中写入数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31367744/

10-13 05:26