本文主要是介绍ReentrantLock可重入锁,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
可重⼊锁,这个锁可以被线程多次重复进⼊进⾏获取操作。
ReentantLock继承接⼝Lock并实现了接⼝中定义的⽅法,除了能完成synchronized所能完成的所有⼯作 外,还提供了诸如可响应中断锁、可轮询锁请求、定时锁等避免多线程死锁的⽅法。
在并发量较⼩的多线程应⽤程序中,ReentrantLock与synchronized性能相差⽆⼏,但在⾼ 并发量的条件下,synchronized性能会迅速下降⼏⼗倍,⽽ReentrantLock的性能却能依然维持⼀个⽔ 准。
因此我们建议在⾼并发量情况下使⽤ReentrantLock。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class Counter {private final Lock lock = new ReentrantLock();private int count = 0;public void increment() {lock.lock(); // 获取锁try {count++;} finally {lock.unlock(); // 释放锁}}public int getCount() {return count;}public static void main(String[] args) {Counter counter = new Counter();// 创建两个线程,模拟并发访问共享资源Thread t1 = new Thread(() -> {for (int i = 0; i < 1000; i++) {counter.increment();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 1000; i++) {counter.increment();}});t1.start();t2.start();// 等待两个线程执行完毕try {t1.join();t2.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Final count is: " + counter.getCount());}
}
public class Counter {private int count = 0;// 使用 synchronized 关键字修饰方法,确保线程安全public synchronized void increment() {count++;}public int getCount() {return count;}public static void main(String[] args) {Counter counter = new Counter();Thread t1 = new Thread(() -> {for (int i = 0; i < 1000; i++) {counter.increment();}});Thread t2 = new Thread(() -> {for (int i = 0; i < 1000; i++) {counter.increment();}});t1.start();t2.start();try {t1.join();t2.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Final count is: " + counter.getCount());}
}
这篇关于ReentrantLock可重入锁的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!