我需要你的建议。我正在尝试制作一些可以批量检查av的代码。连接速度到多个线程中的URL。代码有效。但是我不明白为什么当我使用4个线程时,av.connection速度是150ms并且使用20个线程它可以提升到500-600ms?有线索吗?
下面的代码应该如何工作的想法:主要是我启动一个“ThreadManager”,它启动多个将与URL建立连接的线程。 URL保存在同步的ArrayList中,结果也写在同步的ArrayList中。
package URLConnectionSpeedChecker;
public class ThreadManager implements Runnable{
private static Base base;
@Override
public void run() {
base = new Base();
Thread[] threads = new Thread[4];
for (int i = 0; i < 4; i++ ) {
CheckerThread checkerThread = new CheckerThread(base);
Thread thread = new Thread(checkerThread);
threads[i] = thread;
}
for (Thread x : threads) {
x.start();
}
for (Thread x : threads) {
try {
x.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static Base getBase (){
return base;
}
在线程中运行的代码:
package URLConnectionSpeedChecker;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class CheckerThread implements Runnable {
private static Base base;
CheckerThread(Base base) {
this.base = base;
}
@Override
public void run() {
while (base.getIsOutlistOfURLs() == false) {
long timeDifference = 0;
try {
timeDifference = connectTime(base.getListOfUrls());
} catch (SocketTimeoutException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
addTimeDifference(base.getListOfTimeDifferences(), timeDifference);
}
}
public long connectTime(ArrayList<String> list) throws IOException {
long startTime = 0;
long finishTime = 0;
long timeDifference;
URL url = getURL(list);
if (!(url == null)) {
startTime = System.currentTimeMillis();
URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.connect();
finishTime = System.currentTimeMillis();
timeDifference = finishTime - startTime;
return timeDifference;
} else {
return 0;
}
}
synchronized public void addTimeDifference(ArrayList<Long> list, long timeDifference) {
list.add(timeDifference);
}
synchronized public URL getURL(ArrayList<String> list) {
if (list.size() > 0) {
if (list.get(0).length() > 0) {
URL url = null;
try {
url = new URL(list.get(0));
} catch (MalformedURLException e) {
e.printStackTrace();
}
list.remove(0);
return url;
} else if (list.get(0).length() < 0) {
list.remove(0);
return null;
} else {
return null;
}
} else {
base.setIsOutlistOfURLs();
return null;
}
}
}
}