我對同步實例方法和靜態方法感到困惑。 我想寫一個線程安全類如下:靜態和實例方法上的同步
public class safe {
private final static ConcurrentLinkedQueue<Object> objectList=
new ConcurrentLinkedQueue<Object>();
/**
* retrieves the head of the object and prints it
*/
public synchronized static void getHeadObject() {
System.out.println(objectList.peek().toString());
}
/**
* creates a new object and stores in the list.
*/
public synchronized void addObject() {
Object obj=new Object();
objectList.add(obj);
}
}
同步的靜態方法將鎖定safe.class鎖和一個實例方法同步將鎖定在此。而因此不一致的狀態將達到。
如果我想爲下面的代碼片段實現一致的狀態,那麼如何實現?
爲什麼'addObject'一個實例方法?爲什麼不靜態?爲什麼你要同步一個併發對象呢?他們已經是線程安全的。 – Wug
你的意思是不一致的狀態是什麼? –
我假設他的意思是'隊列