2013-04-10 82 views
1

我有imageurl数组,下载由DownloadFromUrl函数调用,myfunction调用,我使用线程,我不知道有多少图像url,为每个图像下载单独创建线程,我想在所有这些线程结束后开始一个活动。我如何检查动态线程是否结束

我怎么能得到所有这些线程,线程睡眠时间更长无法运行它不是一个好的程序。我也不能计算线程结束由静态变量计数,因为有时图像无法下载或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 
} 

回答

2

ALTERNATIVE 1:使用ExecutorServiceshutdown()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(); 

这将在每次执行递增1锁存器的值。

+0

好主意,thnaks – 2013-04-11 04:44:52

1

而不是创建运行的每一个新的线程,你可能需要使用一个ThreadPoolExecutorexecute方法,这样就可以重用线程,一旦他们完成他们的工作。

至于确定线程何时完成,请使用静态ConcurrentLinkedQueue来跟踪成功的完成情况,并使用另一个静态ConcurrentLinkedQueue来跟踪可能需要重试的不成功完成。然后在你的run()方法,你将包括代码

public void run() { 
    try { 
     ... 
     successfulCompletionQueue.offer(this); 
    } catch (Exception ex) { 
     unsuccessfulCompletionQueue.offer(this); 
    } 
} 

其中this是任何记录信息是相关于手头的任务。

1

要确定整理,请使用asynctask,onPostExceute()方法您可以确保所有图像都已下载,如果您需要进行下载以在下载时使用图像,还可以检查进度。

as 方法在ui线程中运行,现在不应该有任何问题。

但是请记住同样的asynctask不能执行多次。在这种情况下,你有两个选择:

  1. 下载的所有图像asynctastask和更新,其活动onPostExecute()
  2. 为每次下载执行单独asynctask。并使用每个onPostExecute()来更新活动。
+0

我打电话给asloctask forloop吗?或者asynck任务会为每次下载调用forllop? – 2013-04-10 19:27:50

+1

只需从doInBackground()中的asynctask调用myfunction()就可以。 – 2013-04-10 19:36:11