廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock
2020-12-13 01:43
标签:out except 替代 `` system class current port nal 线程同步: 所以Java提供了java.util.concurrent包: java.util.locks.ReetrantLock用于替代synchronized加锁 final Lock lock = new ReetrantLock() tryLock()可指定超时 廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock 标签:out except 替代 `` system class current port nal 原文地址:https://www.cnblogs.com/csj2018/p/11007060.html
```#java
synchronized(lockObj){
n = n + 1;
}
lock.lock()
try{
n = n + 1;
}finally{
lock.unlock();
}import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Lock;
class Counter{
private Lock lock = new ReentrantLock();
private int value = 0;
public void add(int m){
lock.lock();
try{
value += m;
}finally {
lock.unlock();
}
}
public void dec(int m){
lock.lock();
try{
value -= m;
}finally {
lock.unlock();
}
}
public int get(){
lock.lock();
try{
return this.value;
}finally {
lock.unlock();
}
}
}
public class Main{
final static int LOOP = 100;
public static void main(String[] args) throws Exception{
Counter counter = new Counter();
Thread t1 = new Thread(){
public void run(){
for(int i=0;i
总结:
ReentrantLock可以替代synchronized
ReentrantLock获取锁更安全
获取锁在try...finally之前
必须使用try... finallu保证正确释放锁
文章标题:廖雪峰Java11多线程编程-3高级concurrent包-1ReentrantLock
文章链接:http://soscw.com/essay/24102.html