为什么我用两个线程操作一个list,一个不断的删除,一个不断的添加。
会导致
Exception in thread "Thread-0" java.util.NoSuchElementException
at java.util.LinkedList.remove(LinkedList.java:788)
at java.util.LinkedList.removeFirst(LinkedList.java:134)
at SynlistTest.remove(SynlistTest.java:10)
at SynlistTest$1.run(SynlistTest.java:27)
at java.lang.Thread.run(Thread.java:619)
[code="java"]
public class SynlistTest {
LinkedList<String> items = new LinkedList<String>();
public String remove() {
if (!items.isEmpty()) {
return items.removeFirst();
}
return null;
}
public void add(String item) {
items.add(item);
}
public void test() {
Runnable thread1 = new Runnable() {
public void run() {
while (true) {
remove();
}
}
};
Runnable thread2 = new Runnable() {
public void run() {
while (true) {
add("sanyun");
}
}
};
new Thread(thread1).start();
new Thread(thread2).start();
}
public static void main(String[] args) {
new SynlistTest().test();
}
}
[/code]