【发布时间】:2020-05-23 09:30:44
【问题描述】:
假设我有一个保存元素列表的程序,并且我希望能够让任意数量的线程执行作业并保持程序线程安全。
class Program() {
List<Object> list = new ArrayList<Object>();
readFromList(int index) {
synchronized(list.get(index)) { //If i exclude this lock can other threads access the element
Object tmp = list.get(index); //if the lock in writeToList() is active?
return tmp;
}
}
writeToList(int index, Object obj) {
synchronized(list.get(index)) {
list.set(obj);
}
}
那么是否有可能在ArrayList 上保留每个索引的锁,并且当不同的线程想要访问列表中的对象时,它们只需要等待数组中特定元素上的锁吗?
【问题讨论】:
-
快速建议:这有帮助吗? stackoverflow.com/questions/46436946/…
-
您实际上是通过锁定元素来确保什么?您的
readFromList元素从列表中获取项目,然后立即释放锁;所以,我能想象你在这里唯一希望的是直到上次使用writeToList编写元素时的可见性。 -
@AndyTurner 'readFromList' 中的锁只是为了确保线程在写入时不会读取值。
-
list(i) = obj;语法无效 -
@AndyTurner ...并且此构造无法保证可见性。
标签: java multithreading concurrency thread-safety locking