在併發訪問List時,以下代碼是線程安全的嗎?
揮發性限定在這裏添加任何值嗎?使用布爾值進行同步
class concurrentList{
private AtomicBoolean locked = new AtomicBoolean(true);
volatile List<Integer> list=new LinkedList<Integer>();
long start = System.currentTimeMillis();
long end = start + 60*100;
public void push(int e){
while(!locked.get());
list.add(e);
while(!locked.compareAndSet(true,false));
}
public int pop(){
int elem;
while(locked.get());
elem=(Integer)list.remove(0);
while(!locked.compareAndSet(false,true));
return elem;
}
....
}
不確定爲什麼'push'和'pop'方法有不同的鎖定條件。但是從這一點開始,爲什麼不使用['java.util.concurrent.Lock'](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html ?is-external = true)對象? – n247s