0

I have this code:

public class JsoupParser {      
    ArrayList<CompanyInfo> arr = new ArrayList<CompanyInfo>();

    public JsoupParser() {}

    public ArrayList<CompanyInfo> parse(final String link) throws IOException {
        Runnable runnable = new Runnable() {
            public void run() {
                // Here I do some operations and then assign some value
                // to my `arr` ArrayList
            }
        };
        new Thread(runnable).start();

        return arr; // error here, as expected      
    }
}

System immediately returns arr, which at that point is null.

How can I return arr only after Thread finishes? How can I be informed, that Thread has finished?

azizbekian
  • 60,783
  • 13
  • 169
  • 249

2 Answers2

1

The whole point of using another thread, is to have it run while your main thread does something else. If you want your parse method to return the array when it's done, it shouldn't start another thread.

However, since I suppose you do want the calculation to take place in the background, you need to do something else. Why don't you take a look at AsyncTask? It is probably what you need.

zmbq
  • 38,013
  • 14
  • 101
  • 171
1

How can I return arr only after Thread finishes? How can I be informed, that Thread has finished?

Thread parseThread = new Thread(runnable).start();

parseThread.join();

return arr;

There's the literal answer to your question but zmbq's answer is more fitting for what you're after.

Grambot
  • 4,370
  • 5
  • 28
  • 43