Reputation: 51
I have to build a java application which return the names of pdf files in Directory and SubDirictory using threads and it had done. but in addition I've to print it with un alphabetical order. I have write this code which sort the result of each thread but didn't sort the finale result.
public class Pdf extends Thread {
File f;
ArrayList<String> a = new ArrayList<>();
public Pdf(File f, String name) {
super(name);
this.f = f;
}
ArrayList<String> a1 = new ArrayList<>();
@Override
public synchronized void run() {
for (File file : f.listFiles()) {
if (file.isFile() && file.getName().contains(".pdf")) {
if (file.getName().charAt(0) >= 'a' && file.getName().charAt(0) <= 'z') {
Collections.sort(a);
a.add(file.getName());
}
}
if (file.isDirectory()) {
new Pdf(file, file.getName()).start();
}
}
Collections.sort(a);
Collections.reverseOrder();
for (String l : a) {
System.out.println(l);
}
}
}
Upvotes: 1
Views: 100
Reputation: 95
You will need a collection that all threads will add their results to. Make sure that that collection is a synchronized one. Otherwise, the collection could "break". Then, you must wait until all threads are finished. Once they are, you must then sort the collection they added to and return that.
Upvotes: 1
Reputation: 54672
When there is a directory then you are creating a new thread
. That thread is calculating the files and add those in it's own local variable list. The list is sorted for one thread but as there are several different lists for different threads so you can't get a sorted result as a whole. Also as the different threads will be running separately so you can get random outputs of file names.
TO overcome this you can do either of the followings.
Also one a different note if you want to reverse the list then you have to call Collections.reverseOrder(a)
Upvotes: 2