how
java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyRunnable implements Runnable {
private int count = 0;
private final Lock lock = new ReentrantLock(true);
@Override
public void run() {
lock.lock();
try {
count++;
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
} finally {
lock.unlock();
}
}
}
java
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyRunnable implements Runnable {
private int count = 0;
private final Lock lock = new ReentrantLock();
@Override
public void run() {
boolean b = lock.tryLock();
try {
if (b) {
count++;
}
} finally {
lock.unlock();
}
}
}
when
Java锁机制浅析:到底什么情况下该用ReentrantLock?-51CTO.COM
公平锁
代码嵌套且每一层加同一个锁
源码
java
构造方法
参数为false是非公平锁,非公平锁是一个静态内部类继承Sync AQS实现的,先通过CAS修改state变量为1,如果失败,就将线程封装为Node加入双向队列
参数为true是公平锁,公平锁是一个静态内部类继承Sync实现的,线程先进入双向队列,然后再通过CAS修改state变量为1
java
lock()
公平锁
非公平锁
java
tryLock()
尝试加锁,如果失败,就继续执行下面的代码