2012-12-11 140 views
1

我需要下載(無論是從互聯網或從我的緩存)lot的圖像。因此,我決定創建一個下載器線程,使圖像排隊,並在圖像下載時通知調用者。 線程下載隊列中的所有圖像,並等待更多圖像下載。在add方法,我喚醒線程了,開始重新下載:同步:ImageDownloader線程

public class ImageDownloader implements Runnable { 

private boolean continueFetching; 
private List<Image> images; 

private static ImageDownloader instance = new ImageDownloader(); 

private ImageDownloader() { 
    continueFetching = true; 
    images = new ArrayList<Image>(); 

    new Thread(this).start(); 
} 

public static ImageDownloader getInstance() { 
    return instance; 
} 

@Override 
public void run() { 
    synchronized (this) { 
     while (continueFetching) { 
      fetchAvailableImages(); 
      try { 
       this.wait(); 
      } catch (InterruptedException e) { 
      } 
     } 
    } 
} 

private void fetchAvailableImages() { 
    while (images.size() != 0) { 
     Image image = images.get(0); 

        Bitmap bitmap = downloadImage(image); 
        image.onImageDownloadCompleteListener.onImageDownloadComplete(bitmap); 

     images.remove(0); 
    } 
} 

public void stop() { 
    synchronized (this) { 
     continueFetching = false; 
     notify(); 
    } 
} 

public void add(Image image) { 
    images.add(image); 
      notify; 
} 

public interface OnImageDownloadCompleteListener { 

    public void onImageDownloadComplete(Bitmap bitmap); 
} 
} 

當我同步add方法,UI線程掛起,因爲它需要等待完成當前圖像下載。 所以我刪除了同步塊,但現在我得到了java.lang.IllegalMonitorStateException: object not locked by thread before notify()

我該如何解決這個問題?

+0

使用此:-https://github.com/adig/RemoteImageView –

回答

0
  1. 通知修改,以notifyAll的..
  2. 當點擊UI /行動,創建一個新的線程...但是,性能很慢,因爲一旦操作創建一個新的線程...