【发布时间】:2011-07-15 00:36:38
【问题描述】:
在我的 Android 应用程序中,我使用初始 Activity 通过 ASyncTask 进行加载启动,然后启动 mainactivity 下载大约 10 张图像并在表格中将其显示给用户。 我今天刚开始研究 DDMS 和调试模式,我发现在应用程序加载后,我有一个用于 asynctask 的线程和 10 个 http 线程在等待。这正常吗?他们不应该在执行最后一条指令后死掉吗?
这是我的代码:
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();
}
【问题讨论】:
标签: java android multithreading thread-safety android-asynctask