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?
代言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();
}