[英]Two threads call same code even if it is synchronized
I get an exception:我得到一个例外:
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)
and the exception is when I try to remove element from the list then get the first one.例外是当我尝试从列表中删除元素然后获取第一个元素时。 The problem is that a thread want to access that first element when there is already no elements in the list.
问题是当列表中已经没有元素时,线程想要访问第一个元素。 But I did put
synchronized
in method stub.但是我确实将
synchronized
放在了方法存根中。 What is wrong?怎么了?
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
}
}
This doesn't have to be a threading problem.这不一定是线程问题。
Look at the sequence of calls again:再看一下调用顺序:
// 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);
}
Here you check that the list has at least 1 element, then remove an element, then try to retrieve another.在这里,您检查列表是否至少有 1 个元素,然后删除一个元素,然后尝试检索另一个元素。 This will throw an exception if the list's size was 1.
如果列表的大小为 1,这将引发异常。
That's assuming that ISTA
/ LIST
/ LISTA
are all the same thing and those are just typos.那是假设
ISTA
/ LIST
/ LISTA
都是一样的东西,而那些只是拼写错误。 (Otherwise, if they are different, then you are checking the size of the wrong list...) (否则,如果它们不同,那么您正在检查错误列表的大小......)
The snippet is too small to tell what the right way to fix it is and it should frankly be trivial for you to solve.该代码段太小,无法说明修复它的正确方法是什么,坦率地说,它应该很容易解决。
You either need to:您要么需要:
This is a problem with the way you are trying to access the element.这是您尝试访问元素的方式的问题。 You can try using below approach.
您可以尝试使用以下方法。
if (LISTA.size() > 0) {
LISTA.remove(0);
if(LISTA.size() >= 1){
LISTA.get(0).getInijcaly();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.