等到线程优雅地完成 [英] Wait until thread finishes gracefully
本文介绍了等到线程优雅地完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码:
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.
这篇关于等到线程优雅地完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文