我有 imageurl 数组,通过 DownloadFromUrl 函数下载,从我的函数调用,我使用线程,我不知道有多少图像 url,对于创建的每个图像下载单独的线程,毕竟我想开始一个 Activity 这些线程结束。
我怎么能得到所有这些线程,线程 sleep 时间越长就不能工作,这不是一个好的程序。我也不能通过静态变量计数计算到线程结束,因为有时图像无法下载或 url 损坏,或者连接未超时,
我现在有点迷茫了,弄清楚这些所有线程都结束的程序是什么?
public void DownloadFromUrl(String DownloadUrl, String fileName) {
try {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/"+Imageurl.facebookpage);
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL(DownloadUrl); //you can write here any link
File file = new File(dir, fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
LoginActivity.statsofdownload++;
Log.d("DownloadManager","file://"+file.getAbsolutePath());
} catch (IOException e) {
Imageurl.pagestat="space";
Log.d("DownloadManager", "Error: " + e);
}
}
myfunction()
{
for(String string : Imageurl.output) {
imagea++;
final int ind =imagea;
final String ss=string;
new Thread(new Runnable() {
public void run() {
DownloadFromUrl(ss,"IMAGE"+ind+".jpeg");
File root = android.os.Environment.getExternalStorageDirectory();
Imageurl.newyearsvalues.add("file://"+root.getAbsolutePath() + "/"+Imageurl.facebookpage+ "/"+"IMAGE"+ind+".jpeg");
}
}).start();
}
//// now need to call an activity but how I will know that these thread all end
}
最佳答案
备选方案 1:将 ExecutorService
与 shutdown()
和 awaitTermination()
一起使用:
ExecutorService taskExecutor = Executors.newFixedThreadPool(noOfParallelThreads);
while(...) {
taskExecutor.execute(new downloadImage());
}
taskExecutor.shutdown();
try {
taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
...
}
基本上,shutdown()
所做的是阻止 ExecutorService
接受任何更多的线程请求。
awaitTermination()
等待直到 ExecutorService
完成所有线程的执行。
备选方案 2:使用 CountDownLatch
:
CountDownLatch latch = new CountDownLatch(totalNumberOfImageDownloadTasks);
ExecutorService taskExecutor = Executors.newFixedThreadPool(noOfParallelThreads);
while(...) {
taskExecutor.execute(new downloadImage());
}
try {
latch.await();
} catch (InterruptedException E) {
// handle
}
并在您的 imageDowloader() 函数中添加一行:
latch.countDown();
这将在每次执行时将 latch 的值递增 1。
关于java - 我如何检查动态线程是否结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15934419/