1 可重入鎖 (ReentrantLock和synchronized)
可重入鎖指的是可重復可遞歸調(diào)用的鎖,在外層使用鎖之后,在內(nèi)層仍然可以使用,并且不發(fā)生死鎖,這樣的鎖就叫做可重入鎖
如ReentrantLock和synchronized都是可重入鎖的
如:
public class ReentrantTest1 implements Runnable {
public synchronized void get() {
System.out.println(Thread.currentThread().getName());
set();
}
public synchronized void set() {
System.out.println(Thread.currentThread().getName());
}
public void run() {
get();
}
public static void main(String[] args) {
ReentrantTest1 rt = new ReentrantTest1();
for(;;){
new Thread(rt).start();
}
}
}
輸出結(jié)果,沒有死鎖
Thread-8492
Thread-8492
Thread-8494
Thread-8494
Thread-8495
Thread-8495
Thread-8493
Thread-8493
2 不可重入鎖
簡單說就是不可重入鎖,與可重入鎖相反,不可遞歸調(diào)用,否則遞歸調(diào)用就發(fā)生死鎖
import java.util.concurrent.atomic.AtomicReference;
public class UnreentrantLock {
private AtomicReference<Thread> owner = new AtomicReference<Thread>();
public void lock() {
Thread current = Thread.currentThread();
//這句是很經(jīng)典的“自旋”語法,AtomicInteger中也有
for (;;) {
if (!owner.compareAndSet(null, current)) {
return;
}
}
}
public void unlock() {
Thread current = Thread.currentThread();
owner.compareAndSet(current, null);
}
}
上面代碼,如果第一次lock了,在第一次unlock前,又進行第二次lock,則發(fā)生死循環(huán),即死鎖
改造一下就變成可重入鎖了
import java.util.concurrent.atomic.AtomicReference;
public class UnreentrantLock {
private AtomicReference<Thread> owner = new AtomicReference<Thread>();
private int state = 0;
public void lock() {
Thread current = Thread.currentThread();
if (current == owner.get()) {
state++;
return;
}
//這句是很經(jīng)典的“自旋”式語法,AtomicInteger中也有
for (;;) {
if (!owner.compareAndSet(null, current)) {
return;
}
}
}
public void unlock() {
Thread current = Thread.currentThread();
if (current == owner.get()) {
if (state != 0) {
state--;
} else {
owner.compareAndSet(current, null);
}
}
}
}