简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM