非空列表上的NoSuchElementException [英] NoSuchElementException on non empty list

查看:72
本文介绍了非空列表上的NoSuchElementException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式创建了一个可运行对象:

I have a runnable created this way:

private Runnable _animationScriptRunnable = new Runnable() {
    public void run() {
        synchronized (AnimationManager.this) {
            while (!_stopRunning && !_animationScriptStack.isEmpty()) {
                Class key = _animationScriptStack.removeFirst();
                if (isAnimationExist(key) && isAnimationActivated(key)) {
                    AAnimation animation = _animationsClassTable.get(key);
                    animation.doBeforeAnimation();
                    animation.onAnimationBeginning();
                    do {
                        animation.onAnimation();
                    } while (isAnimationActivated(key) && animation.isAnimationRecurent() && !_stopRunning);
                    animation.onAnimationEnding();
                    animation.doAfterAnimation();
                }
            }
        }
    }
};

如您所见,我检入一个同步块,确认我的堆栈(_animationScriptStack,创建为LinkedList<Class<?>> _animationScriptStack)不为空,如果不为空,则删除第一个元素.但是,有时候,我在removeFirst()通话中有一个java.util.NoSuchElementException.

As you can see, I check in a synchronized block that my stack (_animationScriptStack, created as a LinkedList<Class<?>> _animationScriptStack) is not empty, and if it's not, I remove the first element. But, sometimes, I have a java.util.NoSuchElementException, on the removeFirst() call.

有人可以解释为什么吗?

Can someone explain me why?

推荐答案

LinkedList 并非线程安全的,可能在代码中导致意外结果.

LinkedList is not thread safe and probably this is causing un-expected results in your code.

您需要使用 ConcurrentLinkedQueue ,在这种情况下,当您尝试访问线程中的列表时.请看一下,我想这就是您所需要的.

You need to use ConcurrentLinkedQueue in this case as you are trying to access a list in a Thread. Please look at it, I guess this is what you need.

这篇关于非空列表上的NoSuchElementException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆