在第一種方法,我只是想在陣列中創建的每個URL線程,並對其進行分析:爲什麼開始我的線程不會調用run()方法?
public void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for(int x = 0; x< urls.length; x++){
urlThreads[x].start();
}
}
然後我做了一個單獨的類我的Runnable對象,其中run方法創建一個BufferedReader掃描html文件並解析它。
package twitbook;
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public Runobject(String theAdress, Twitbook net) {
address = theAdress;
this.net = net;
}
@Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
我知道何時調用第一個方法,即使我啓動了線程,但它並沒有通過runObject類中的run方法。爲什麼是這樣?
很難相信。你的證據在哪裏? – EJP
附註。 ThreadPools值得考慮。 Executors.newFixedThreadPool –