Simple threaded app breaks on openStream method
// BEGIN TESTURL CLASS
import java.io.*;
public class TestURL {
static boolean listening = true;
public static void main(String[] args) throws IOException {
System.out.println("Starting...");
ImageDownloader id1 = null;
ImageDownloader id2 = null;
id1 = new ImageDownloader("http://www.visnat.com/entry/vnimages/
workplace1.jpg","1");
id2 = new ImageDownloader("http://www.visnat.com/entry/vnimages/
workplace2.jpg","2");
System.out.println("Starting threads...");
id1.start();
id2.start();
System.out.println("After threads...");
}
}
import java.io.*;
public class TestURL {
static boolean listening = true;
public static void main(String[] args) throws IOException {
System.out.println("Starting...");
ImageDownloader id1 = null;
ImageDownloader id2 = null;
id1 = new ImageDownloader("http://www.visnat.com/entry/vnimages/
workplace1.jpg","1");
id2 = new ImageDownloader("http://www.visnat.com/entry/vnimages/
workplace2.jpg","2");
System.out.println("Starting threads...");
id1.start();
id2.start();
System.out.println("After threads...");
}
}
// END TESTURL CLASS
// BEGIN IMAGEDOWNLOADER CLASS
import java.io.*;
import java.net.*;
public class ImageDownloader extends Thread {
private static final boolean DEBUG = true;
private String strUrl;
private String strOutFileName = "memory";
private String TID;
private int i = 0;
public ImageDownloader(String theurl,String threadID) {
strUrl = theurl;
TID = threadID;
}
public void run() {
System.out.println("Starting thread");
URL url;
InputStream is = null;
while(i < 2) {
i++;
try {
long numMillisecondsToSleep = 1000;
Thread.sleep(numMillisecondsToSleep);
} catch (InterruptedException e) {
return;
}
try {
url = new URL(strUrl);
is = url.openStream(); //throws an IOException
} catch (IOException ioe) {
System.out.println(TID + ": the url openstream call failed:" +
ioe);
}
try {
if (DEBUG) System.out.println("Thread " + TID + ": Starting save
of " + strUrl + " to " + strOutFileName + " ...");
BufferedInputStream bis=new BufferedInputStream(is);
byte[] buff = new byte[4096];
byte[] buff2 = new byte[32767];
int bytesRead;
int buff2Offset=0;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
System.arraycopy(buff, 0, buff2, buff2Offset, bytesRead);
buff2Offset += bytesRead;
}
if (DEBUG) System.out.println("Thread " + TID + ": Task " + i+ ":
" + buff2Offset + " bytes read into memory buffer.");
if (DEBUG) System.out.println("Thread " + TID + ": done with task
" + i);
}
catch (Exception e)
{
System.out.println("Exception happened : " + e);
} //END TRY
} //END WHILE
} //END RUN()
}
// END IMAGEDOWNLOADER CLASS