![](/img/trans.png)
[英]Can two threads execute the same synchronized block of code on the same object if they use different monitors?
[英]Two threads call same code even if it is synchronized
我得到一个例外:
Exception in thread "Thread-0" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
例外是当我尝试从列表中删除元素然后获取第一个元素时。 问题是当列表中已经没有元素时,线程想要访问第一个元素。 但是我确实将synchronized
放在了方法存根中。 怎么了?
private static ArrayList<Pracownik> LIST;
public static synchronized void roll(){
if (LIST.size() > 0) {
LISTA.remove(0);//removing from list
String initials = LISTA.get(0).getInijcaly(); //here is exception
}
}
这不一定是线程问题。
再看一下调用顺序:
// check that the list has at least 1 element
if (ISTA.size() > 0) {
// remove 1 element
LISTA.remove(0);
// list might have 0 elements at this point
LISTA.get(0);
}
在这里,您检查列表是否至少有 1 个元素,然后删除一个元素,然后尝试检索另一个元素。 如果列表的大小为 1,这将引发异常。
那是假设ISTA
/ LIST
/ LISTA
都是一样的东西,而那些只是拼写错误。 (否则,如果它们不同,那么您正在检查错误列表的大小......)
该代码段太小,无法说明修复它的正确方法是什么,坦率地说,它应该很容易解决。
您要么需要:
这是您尝试访问元素的方式的问题。 您可以尝试使用以下方法。
if (LISTA.size() > 0) {
LISTA.remove(0);
if(LISTA.size() >= 1){
LISTA.get(0).getInijcaly();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.