I am learning multithread in Java. To practice, I want do multithread to read three txt files in paralel, adding each line of three files into one List. This is my code:
ArrayList<String> allLinesFromFiles= new ArrayList<String>();
Lock blockThread=new ReentrantLock();
Thread t = null;
for (String file : files) {
t= new Thread(new Runnable() {
@Override
public void run() {
try {
FileReader fichero;
fichero = new FileReader(file);
BufferedReader bufferFichero = new BufferedReader(fichero);
String line = bufferFichero.readLine();
while (line != null) {
writeList(line.toLowerCase());
line = bufferFichero.readLine();
}
bufferFichero.close();
}catch (IOException e) {
System.out.println("Error IO");
}
}
private void writeList(String line) {
blockThread.lock();
allLinesFromFiles.add(line);
blockThread.unlock();
}
});
t.start();
}
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Collections.sort(allLinesFromFiles);
I used lock/unlocks (ReentrantLock) in the method "writeList" to synchronize because three threads writting in the ArrayList I thought maybe is needed. Is correct? Have I to use CopyOnWriteArrayList instead of ArrayList?
I used join() to wait the finish of three threads but my code dont work correctly.