简体   繁体   English

等到线程正常完成

[英]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 . 系统立即返回arr ,此时为null

How can I return arr only after Thread finishes? 如何在Thread完成后返回arr How can I be informed, that Thread has finished? 我怎么知道Thread已经完成了?

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. 如果你希望你的parse方法在完成时返回数组,它就不应该启动另一个线程。

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 ? 你为什么不看看AsyncTask It is probably what you need. 这可能就是你所需要的。

How can I return arr only after Thread finishes? 如何在Thread完成后返回arr? How can I be informed, that Thread has finished? 我怎么知道Thread已经完成了?

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. 对你的问题有字面的答案,但zmbq的答案更适合你所追求的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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