java线程状态监视器如何调试?是什么引起的?

fjaof16o  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(284)

我是在android上开发的,我不明白为什么我的一些线程会进入“监视”状态。我读过,这可能是因为一个“同步”的问题,但我不知道一个对象如何不会释放他们的锁。
有人能帮我调试一下吗?或者你看到我做错什么了吗?是因为同步对象没有被释放,还是我的加载没有正确超时并锁定所有线程?

下面是我如何使用synchronized。

private Bitmap getFromSyncCache(String url) {
    if (syncCache == null) return null;
    synchronized (syncCache) {
        if (syncCache.hasObject(url)) {
            return syncCache.get(url);
        } else {
            return null;
        }
    }
}

在这里:

bitmapLoader.setOnCompleteListener(new BitmapLoader.OnCompleteListener() {
            @Override
            public void onComplete(Bitmap bitmap) {
                if (syncCache != null) {
                    synchronized (syncCache) {
                        syncCache.put(bitmapLoader.getLoadUrl(), bitmap);
                    }
                }
                if (asyncCache != null) addToAsyncCache(bitmapLoader.getLoadUrl(), bitmap);
                if (onCompleteListener != null) onCompleteListener.onComplete(bitmap);
            }
        });

这是我的储藏室

public class MemoryCache<T> implements Cache<T>{

private HashMap<String, SoftReference<T>> cache;

public MemoryCache() {
    cache = new HashMap<String, SoftReference<T>>();
}

@Override
public T get(String id) {
    if(!cache.containsKey(id)) return null;
    SoftReference<T> ref = cache.get(id);
    return ref.get();
}

@Override
public void put(String id, T object) {
    cache.put(id, new SoftReference<T>(object));
}

@Override
public void clearCache() {
    cache.clear();
}

@Override
public boolean hasObject(String id) {
    return cache.containsKey(id);
}

我就是这样从网上加载图像的:

private void threadedLoad(String url) {
    cancel();
    bytesLoaded = 0;
    bytesTotal = 0;
    try {
        state = State.DOWNLOADING;
        conn = (HttpURLConnection) new URL(url).openConnection();
        bytesTotal = conn.getContentLength();

        // if we don't have a total can't track the progress
        if (bytesTotal > 0 && onProgressListener != null) {
            // unused               
        } else {
            conn.connect();
            inStream = conn.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inStream);
            state = State.COMPLETE;
            if (state != State.CANCELED) {
                if (bitmap != null) {
                    msgSendComplete(bitmap);
                } else {
                    handleIOException(new IOException("Skia could not decode the bitmap and returned null. Url: " + loadUrl));
                }
            }
            try {
                inStream.close();
            } catch(Exception e) {

            }
        }
    } catch (IOException e) {
        handleIOException(e);
    }
}
chy5wohz

chy5wohz1#

检查是否确实是死锁的一种方法是使用androidstudio的调试器:查看线程,右键单击处于“监视”状态的线程,然后单击“挂起”。调试器会将您带到代码中线程卡住的那一行。

当我调试死锁时,两个线程都在等待同步语句。

相关问题