ReentrantLock(可重入鎖)和synchronized區(qū)別
- 可重入性
- 鎖的實(shí)現(xiàn)(ReentrantLock是JDK實(shí)現(xiàn)仇矾,synchronized是依賴于JVM實(shí)現(xiàn),前者可以閱讀源碼個(gè)人實(shí)現(xiàn))
- 性能的區(qū)別(目前差不多拍棕,傾向于synchronized)
- 功能的區(qū)別
當(dāng)需要使用ReentrantLock的獨(dú)有功能時(shí)使用該鎖
package io.haitaoc.concurrency.example.lock;
import io.haitaoc.concurrency.annotation.ThreadSafe;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@ThreadSafe
public class LockExample2 {
// 請(qǐng)求總數(shù)
public static int clientTotal = 5000;
// 同時(shí)并發(fā)執(zhí)行的線程數(shù)
public static int threadTotal = 200;
public static int count = 0;
private final static Lock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
for (int i = 0; i < clientTotal ; i++) {
executorService.execute(() -> {
try {
semaphore.acquire();
add();
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println("count: "+ count);
}
private static void add() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
package io.haitaoc.concurrency.example.lock;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 悲觀讀取晓铆,執(zhí)行寫入操作堅(jiān)決不允許進(jìn)行讀取操作
* 當(dāng)讀多寫少時(shí),就會(huì)使寫操作進(jìn)入饑餓绰播,一直進(jìn)入阻塞狀態(tài)
*/
public class LockExample3 {
private final Map<String, Data> map = new TreeMap<>();
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
public Data get(String key) {
readLock.lock();
try {
return map.get(key);
} finally {
readLock.unlock();
}
}
public Set<String> getAllKeys() {
readLock.lock();
try {
return map.keySet();
} finally {
readLock.unlock();
}
}
public Data put(String key, Data value) {
writeLock.lock();
try {
return map.put(key, value);
} finally {
readLock.unlock();
}
}
class Data {
}
}