Java SynchronizedList在交换时获取空值
我试图写一个“交换列表”,想想双缓冲区,但对象而不是原始字节。基本上,我这样做是为了减少争用,这样一个任务可以在交换列表添加到中时进行大量删除Java SynchronizedList在交换时获取空值,java,concurrentmodification,Java,Concurrentmodification,我试图写一个“交换列表”,想想双缓冲区,但对象而不是原始字节。基本上,我这样做是为了减少争用,这样一个任务可以在交换列表添加到中时进行大量删除 public class SwapList<T> { List<T> A; List<T> B; volatile boolean swap; public SwapList() { A = Collections.synchronizedList( new ArrayL
public class SwapList<T> {
List<T> A;
List<T> B;
volatile boolean swap;
public SwapList() {
A = Collections.synchronizedList( new ArrayList<T>());
B = Collections.synchronizedList( new ArrayList<T>());
swap = false;
}
public void swap() {
swap = !swap;
}
public List<T> getA() {
return swap ? A : B;
}
public List<T> getB() {
return swap ? B : A;
}
public int size() {
return A.size() + B.size();
}
public void clear() {
A.clear();
B.clear();
}
}
然而,我经常得到一个意想不到的[“A”、“A”、“A”、null、“A”、“A”、…]
空值从何而来?您是如何获得打印列表的?你是如何调用独立的线程的?这真的很奇怪,因为它是一个同步的列表,而你只调用了'add(a)'或'add(B)'。是否有其他线程可以添加/设置其他数据?
// declared statically in same package
public static SwapList<String> list = new SwapList<>();
// one thread does this
int i = 1000;
while( i-- > 0 ) {
list.getA().add("A");
// another thread does this
int i = 1000;
list.swap();
while( i-- > 0 ) {
list.getB().add("B");
Thread b = new Thread() {
@Override
public void run() {
int i = lim; // lim is some int
list.swap(); // only the second one will call swap
while( i-- > 0 ) {
list.getB().add("B");
}
}
};
// later
a.start();
b.start();
a.join();
b.join();
System.out.println( list.getA() );