我有一个具有以下方法的代码:
downloadFile() - 从 ftp 服务器下载文件
processFile() - 逐行读取文件并处理该行
sendSMS() - 向供应商发送短信以处理已处理的记录数。
processFile
方法读取每一行,构建 URL 字符串并命中 URL。为了使过程更快,我使用了线程概念。
//snippet in processFile method
while ((sCurrentLine = br.readLine()) != null) {
String[] arr = sCurrentLine.split("\t");
if (//some condition) {
String url = //build url from the current line
Thread t = new Thread(new MyClass(url));
t.start();
}
}
public MyClass(String strUrl) {
this.strUrl = strUrl;
}
public void run() {
urlHit(strUrl);//call function to hit current URL
}
现在我担心的是 sendSMS
方法应该仅在所有 URL 都被命中后才被调用。
我尝试使用 join
方法,该方法工作正常,但与不使用线程一样好。
最佳答案
你需要应用同步,并且在java中有多种应用同步的方法。您可以使用 wait()
和 notify()
,其中 sendSms 会等待,直到收到 URL 已被命中的通知。
检查示例here来帮助你。
关于java - 循环调用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298311/