同步:ImageDownloader线程

时间:2012-12-11 14:21:50

标签: java android synchronization

我需要下载(从互联网或我的缓存中)很多的图片。因此,我决定创建一个下载程序线程,它将图像排入队列并在下载图像时通知调用者。 线程下载队列中的所有图像,并等待下载更多图像。在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()

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

更好的解决方案是使用这个处理图像下载的漂亮库:)

用户易于使用且也是开源的: https://github.com/nostra13/Android-Universal-Image-Loader

为什么发明轮子两次? :)

答案 1 :(得分:0)

我使用此源https://github.com/thest1/LazyList效果很好,异步加载图像;)

我希望能帮到你

答案 2 :(得分:0)

  1. 通知修改为notifyAll ..
  2. 点击UI /动作时,创建一个新线程......但是,性能很慢,因为一旦动作创建一个新线程......
相关问题