2014-03-31 41 views
-2

我得到一個異常同一代碼:兩個線程調用,即使它是同步

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) 

和例外的是,當我嘗試從列表中刪除元素然後得到的第一個。問題是一個線程想要在列表中沒有元素時訪問第一個元素。但我確實在方法存根中放入了​​。哪裏不對?

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 
     } 

    } 
+0

你是怎麼調用這段代碼的。另外'LISTA.size()'看起來像是通過NPE –

+0

你能告訴我哪一行出現錯誤嗎? – Levenal

+0

如果這是最後一個元素,那麼您將從列表中刪除元素,在下一行您將嘗試從空列表中檢索元素。 – enterbios

回答

6

這並不一定是一個線程問題。

看來電再次序列:

// 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都是同樣的事情,這些僅僅是錯別字這會拋出異常。 (否則,如果他們不同,那麼你正在檢查錯誤列表的大小......)

該片段太小,不能告訴正確的方法來解決它是什麼,它應該坦率地爲你微不足道解決。

你要麼需要:

  • 檢查列表中有訪問這些兩件事情之前至少兩件事情。
  • 檢查至少有1件事情,只訪問1件事情。
0

這是您嘗試訪問元素的方式的問題。你可以嘗試使用下面的方法。

if (LISTA.size() > 0) { 
     LISTA.remove(0); 
     if(LISTA.size() >= 1){ 
      LISTA.get(0).getInijcaly(); 
     } 
    }