我需要(从互联网或我的缓存)下载很多图像。因此,我决定创建一个下载器线程,它将图像排入队列并在下载图像时通知调用者。该线程下载队列中的任何图像,并等待下载更多图像。在add
方法中,我唤醒线程重新开始下载:
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()
.
我该如何解决这个问题?