我有这样的课程(删除了不相关的代码):
public final class Card {
private boolean important;
public boolean isImportant() {
return important;
}
public void setImportant(boolean isImportant) {
this.important = isImportant;
fireIsImportantChangedEvent(isImportant);
}
private EventListenerList listenerList = new EventListenerList();
private void fireIsImportantChangedEvent(boolean newValue) {
for (CardListener listener : listenerList.getListeners(CardListener.class)) {
listener.isImportantChanged(new CardEvent<Boolean>(this, newValue));
}
}
}
我正在尝试使此类线程安全,但不确定是否需要同步访问重要(public synchronized boolean isImportant() { ... }
和public synchronized void setImportant(boolean isImportant) { ... }
)的任何方法,或者只是声明重要的易失性(private volatile boolean important;
)。我的理解是,如果setImportant()
不触发事件(如果它刚刚触发this.important = isImportant
), volatile 会起作用,但如果我触发此事件, volatile 仍然会起作用吗?