我对同步实例方法和静态方法感到困惑。我想编写一个线程安全类,如下所示:
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 锁,而在实例方法上同步将在 this 上锁定。因此将达到不一致的状态。
如果我想为下面的代码片段实现一致的状态,如何实现?