in my Android app I use a initial Activity for making a loading splash with an ASyncTask and then launch the mainactivity which downloads about 10 images and shows it to the user in a table. I just sta开发者_JAVA技巧rted today to investigate the DDMS and the debug mode and I see that after the app load, I have one thread for the asynctask and 10 http threads waiting. Is that normal? Shouldn't they die with the last instruction executed?
Here is my code:
public void download (String imageURL, String path, String filename){
new Thread(){
public void run() {
long startTime = System.currentTimeMillis();
try {
//Create the path
new File(path).mkdirs();
//File to download
File file = new File(path+filename);
if (!file.exists()){
Log.d(Manager.getAppName(),file.getName()+" dont exists");
URL url = new URL(imageURL);
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
bis.close();
fos.close();
is.close();
Log.d(Manager.getAppName(), "download ready in "
+( (float)(System.currentTimeMillis() - startTime) / 1000f)
+ " sec");
} else {
Log.d(Manager.getAppName(),"File exists (ignoring)");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (latch!=null){
latch.countDown();
Log.d(Manager.getAppName(),"Download finished "+latch.getCount()+" remaining");
}
}
}).start();
}
Threads will not die if they are part of a Thread Pool. Are you starting them yourself?
This is the correct behavior as AsyncTask and libraries like okhttp use thread pool. Depending on the system, there will be a max number of threads that can be in the pool. Whenever a new thread is needed (like when a new AsyncTask is created), one of the idling threads from the pool will be used thereby preventing the overhead involved in creating a new thread every time. Once the task finishes, the thread returns to the idle state in the pool with status "wait".
精彩评论