是否可以通过Java中的ArrayList中的索引锁定单个元素?

假设我有一个保留元素列表的程序,并且希望能够有任意数量的执行作业的线程并保持程序的线程安全。

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(i) = obj;
        }
    }

So would it be possible to keep locks per index on the ArrayList and when the different threads want to access objects in the list they will only have to wait for locks on specific elements in the array?

这样的方法行得通吗?

class Program() {

    ArrayList<Object> list = new ArrayList<Object>();
    ArrayList<ReadWriteLock> rwl = new ArrayList<ReadWriteLock();

    readFromList(int index) {
        Lock lock = rwl.get(index).readLock();
        lock.lock();
        Object tmp = list.get(index);
        lock.unlock();
        return tmp;

    }

    writeToList(int index, Object obj) {
        Lock lock = rwl.get(index).writeLock();
        lock.lock();
        list(i) = obj;
        lock.unlock();
    }
评论