2013-04-10 17 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

相關問題