Tag nedenstående kode og sammenlign med din egen. Lars
java version "1.4.1_02"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_02-b06)
Java HotSpot(TM) Client VM (build 1.4.1_02-b06, mixed mode)
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class UrlTest {
private static final int NUMBER_OF_THREADS = 25;
private Thread[] threads = new Thread[NUMBER_OF_THREADS];
private static Thread create() {
return new Thread() {
public void run() {
BufferedReader in = null;
try {
URL u = new URL("http","
www.eksperten.dk",80,"/spm/350101");
URLConnection connection = u.openConnection();
InputStream inTemp = connection.getInputStream();
if (inTemp == null) {
System.err.println("Unable to read the server result");
return;
} else {
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
int count = 0;
ArrayList strings = new ArrayList();
while (in.ready()) {
strings.add(in.readLine());
count++;
}
System.out.println("Thread "+this.getName()+" read "+count+" lines");
if (this.getName().equals("Thread-1")) {
System.out.println("Read:");
int size = strings.size();
for (int i=0; i<size; i++) {
System.out.println((String) strings.get(i));
}
}
}
} catch (MalformedURLException e) {
System.err.println("Thread "+this.getName()+" has failed");
e.printStackTrace();
return;
} catch (IOException e) {
System.err.println("Thread "+this.getName()+" has failed");
e.printStackTrace();
return;
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
System.err.println("Thread "+this.getName()+" has problems while closing the connection");
return;
}
}
}
};
}
public void run() {
System.out.println("Creating threads...");
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
threads[i] = create();
}
System.out.println("Starting threads...");
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
threads[i].start();
}
for (int i = 0; i < NUMBER_OF_THREADS; i++) {
try {
threads[i].join();
System.out.print("x");
} catch (InterruptedException e) {
e.printStackTrace();
System.err.println("Interrupted while waiting");
return;
}
}
System.out.println("");
}
public static void main(String args[]) {
UrlTest urlTest = new UrlTest();
urlTest.run();
}
}