我有一个线程用值填充向量对象,另一个线程定期从中获取值并定期清除它。
我希望访问向量的任一线程暂停,而另一个正在访问它。我需要使用 wait/notify/notifyAll 关键字吗?
private Vector<Long> _recordIdsSent;
# Called by main thread (before thread A and thread B are started)
public ConstructorOfThisClass() {
_recordIdsSent = new Vector<Long>();
// Starts thread A & B
}
# Called by thread A
public void addSentRecordIds( List<Long> ids ) {
synchronized (_recordIdsSent) {
_recordIdsSent.addAll( ids );
}
}
# Called by thread B
public void deleteRecords()
{
List<Long> ids;
synchronized (_recordIdsSent) {
ids = (List<Long>) _recordIdsSent.clone();
_recordIdsSent.clear();
}
// Delete the records matching ids....
}
注意:我克隆了 _recordIdsSent 向量,因为删除操作可能需要一些时间。
[编辑] 将同步关键字从方法签名移动到变量 _recordIdsSent