等到线程优雅地完成
问题描述:
我有这个代码:
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
.
System immediately returns arr
, which at that point is null
.
怎样才能在Thread
结束后返回arr
?如何通知我 Thread
已完成?
How can I return arr
only after Thread
finishes? How can I be informed, that Thread
has finished?
答
如何在线程完成后才返回 arr?我怎么会通知,线程已完成?
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 的答案更适合您的需求.
There's the literal answer to your question but zmbq's answer is more fitting for what you're after.