我正在制作一个简单的程序来从多个网页中抓取内容。我想提高程序的速度,所以我想使用线程。我希望能够用一些整数来控制线程的数量(我希望用户能够定义它)。
这是我要为其创建线程的代码:
public void runLocales(String langLocale){
ParseXML parser = new ParseXML(langLocale);
int statusCode = parser.getSitemapStatus();
if (statusCode > 0){
for (String page : parser.getUrls()){
urlList.append(page+"\n");
}
}else {
urlList.append("Connection timed out");
}
}
和 parseXML 类:
public class ParseXML {
private String sitemapPath;
private String sitemapName = "sitemap.xml";
private String sitemapDomain = "somesite";
Connection.Response response = null;
boolean success = false;
ParseXML(String langLocale){
sitemapPath = sitemapDomain+"/"+langLocale+"/"+sitemapName;
int i = 0;
int retries = 3;
while (i < retries){
try {
response = Jsoup.connect(sitemapPath)
.userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
.timeout(10000)
.execute();
success = true;
break;
} catch (IOException e) {
}
i++;
}
}
public int getSitemapStatus(){
if(success){
int statusCode = response.statusCode();
return statusCode;
}else {
return 0;
}
}
public ArrayList<String> getUrls(){
ArrayList<String> urls = new ArrayList<String>();
try {
Document doc = response.parse();
Elements element = doc.select("loc");
for (Element page : element){
urls.add(page.text());
}
return urls;
} catch (IOException e) {
System.out.println(e);
return null;
}
}
}
几天来我一直在阅读有关线程的信息,但我不知道如何在我的情况下实现线程?有人可以提供一些见解吗?