Home  >  Q&A  >  body text

How does reentrantlock lock a specific object?

If I have an array object with a length of 10:

Object[] arr=new Object[10];

Access to each object is mutually exclusive, but access between multiple objects can be concurrent.
Then use synchonized like this:

synchoronized(arr[i]){
    //...
}

I would like to ask, how to implement such a lock if using reentrantlock?

Note: Do I need to create 10 Lock arrays at the same time for this usage scenario? Lock[] lockList=new ReentrantLock[10]

if(lockList[i].trylock())[
    //
}

so?

扔个三星炸死你扔个三星炸死你2686 days ago861

reply all(1)I'll reply

  • 代言

    代言2017-06-12 09:27:57

    Initialization lock:

    Lock[] lockList = new ReentrantLock[10];
    for (int i = 0; i < 10; i ++) {
        lockList[i] = new ReentrantLock();
    }
    

    When locking is required:

    lockList[i].lock();
    try {
        ...
    } finally {
        lockList[i].unlock();
    }

    reply
    0
  • Cancelreply