In order to maximize the parallelization of the processing of your audio files, I would split this algorithm in two :
- First, read the directory to find the files to process, and store them in a List or array. This would allow to know exactly how many files must be processed (useful for the technical suggestion below).
- Then, for each file found, start a thread to process it with the
thread_reading
job.
To be notified when all files have been processed, I would use a CountDownLatch. Each thread would call countdown()
to tell it has finished ; and the main thread would simply have to wait for those N completion signals.
Here is the main code :
// 1. Gather files
//File folder = new File("E:/project_3/audio/");
File[] fileList = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
// 2. Process the files in parallel
CountDownLatch completionCounter = new CountDownLatch(fileList.length);
for (File file : fileList) {
System.out.println(file.getName());
thread_reading th1 = new thread_reading(file.getName(), completionCounter);
new Thread(th1).start();
}
// 3. Wait for all processes to finish
try {
completionCounter.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
And here is the code for the thread_reading
job :
public class thread_reading implements Runnable {
private final String name;
private final CountDownLatch completionCounter;
public thread_reading(String name, CountDownLatch completionCounter) {
this.name = name;
this.completionCounter = completionCounter;
}
@Override
public void run() {
// ... do stuff ...
System.out.println(name);
// Say it's done
completionCounter.countDown();
}
}