Kasoir Abbas
Kasoir Abbas

Reputation: 51

Thread Java application

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

Answers (2)

Andrew Cahill
Andrew Cahill

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

stinepike
stinepike

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.

  1. If you use separate thread like this then use a common concurrent list which can be sorted after all the threads are finished executing.
  2. It is better to use a single thread. Here instead of creating a separate thread for each subdirectory, just create a method which will add the files in list and will recursively call itself when there is a subdirectory. In this case at the end of thread you can sort the list and print it.

Also one a different note if you want to reverse the list then you have to call Collections.reverseOrder(a)

Upvotes: 2

Related Questions