How does reentrantlock lock a specific object?
扔个三星炸死你
扔个三星炸死你 2017-06-12 09:25:57
0
1
860

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?

扔个三星炸死你
扔个三星炸死你

reply all(1)
代言

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();
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!