gpt4 book ai didi

java - 等待线程正常完成

转载 作者:行者123 更新时间:2023-12-02 07:25:51 25 4
gpt4 key购买 nike

我有这个代码:

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
}
}

系统立即返回arr,此时为null

如何仅在 Thread 完成后才返回 arr?我如何得知Thread已完成?

最佳答案

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;

您的问题有字面答案,但 zmbq 的答案更适合您的需求。

关于java - 等待线程正常完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13593390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com