2016-05-07 12 views
0

複数の画像URLからビットマップを取得してarraylistに追加しようとしていますが、私はこれに以下のコードを使用しています。Androidスレッドの同期

for (int j = 0; j <= imagePaths.size() - 1; j++) { 
        final String urltemp = "http://SiteName/" + imagePaths.get(j); 
        new Thread(new Runnable() { 
         @Override 
         public void run() { 
          try { 
           final URL url = new URL(urltemp); 
           HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
           connection.setDoInput(true); 
           connection.connect(); 
           InputStream input = null; 
           input = connection.getInputStream(); 
           Bitmap myBitmap = BitmapFactory.decodeStream(input); 
           arrayList.add(myBitmap); 
          } catch (IOException e) { 
           e.printStackTrace(); 
          } 
         } 
        }).start(); 
       } 

コードは問題なく動作しますが、ArryListの画像の順序はランダムに変更されます。 forループの内部でスレッドを同期させると、ループの順番で画像が追加されます。

+0

を私はThread.joinを(追加することによってそれを解決した)、私はそれが他のスレッドを待つようになります知っています。 – Manish

答えて

0

1この種のジョブにはスレッドプールを使用する必要があります。 2スレッドを同期させないでください。コンテナクラスにビットマップを格納し、インデックスを格納してから配列を並べ替えるだけです。

1

スレッドカウントの制限がないため、コードは非常に悪いと言って始めましょう。これは、すべてのダウンロードが別のスレッドで行われ、スレッドの実行時間がダウンロードされるイメージのサイズによって異なるためです。

しかし、あなたはまだこの道を行くにしたい場合は、このコードを使用します

ArrayList<Bitmap> arrayList = new Arraylist<~>[imagePaths.size()] 
for (int j = 0; j <= imagePaths.size() - 1; j++) { 
       final String urltemp = "http://SiteName/" + imagePaths.get(j); 
       new Thread(new Runnable() { 
        @Override 
        public void run() { 
         try { 
          final URL url = new URL(urltemp); 
          HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
          connection.setDoInput(true); 
          connection.connect(); 
          InputStream input = null; 
          input = connection.getInputStream(); 
          Bitmap myBitmap = BitmapFactory.decodeStream(input); 

          //here is the change 
          arrayList.add(j, myBitmap); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
        } 
       }).start(); 
      }