azizbekian azizbekian -4 years ago 50
Java Question

Wait until thread finishes gracefully

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download