Search code examples
javamultithreadingarraylistrunnable

How to use a method in Multi-Threads Class which implements Runnable


I am making a multi-threaded application. The class which implements Runnable has a method which returns ArrayList. How do i use that method in my main?

class SearchThread implements Runnable {

   private ArrayList<String> found;

   //Constructor
   public SearchThread (String[] dataArray) {/**/}

   public void run() {
        try{
            //Do something with found
            }
            Thread.sleep(time);
            System.out.println("Hello from a thread!");
        }
        catch (Exception e){} 
   }
   public ArrayList<String> getResult() {
         return found;
   }
}

Main class which need to use the getResult method.

ArrayList<String> result;
Thread[] threads = new Thread[data.length];

for (int i = 0; i < data.length; i++) {
    threads[i] = new Thread(new SearchThread(data[i]));
    threads[i].start();
}

try {
    for (int i = 0; i < data.length; i++) {
        threads[i].join();
        result = // need to use the getResult()
    }
} catch (Exception e) {
}

Solution

  • You could to store the references to the SearchThread's in another array and access them after the corresponding thread has joined. I give an example:

    ArrayList<String> result;
    Thread[] threads = new Thread[data.length];
    SearchThread[] searchThreads = new SearchThread[data.length];
    
    for (int i = 0; i < data.length; i++) {
        searchThreads[i] = new SearchThread(data[i]);
        threads[i] = new Thread(searchThreads[i]);
        threads[i].start();
    }
    
    try {
        for (int i = 0; i < data.length; i++) {
            threads[i].join();
            result.add(i, searchThreads[i].getResult() ? "found"
                    : "not found");
        }
    } catch (InterruptedException e) {
        // do something meaningful with your exception
    }