重入锁
锁作为并发共享数据,保证一致性的工具,在JAVA平台有多种实现(如 synchronized 和 ReentrantLock等等 ) 。这些已经写好提供的锁为我们开发提供了便利。
重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响。
在JAVA环境下 ReentrantLock 和synchronized 都是 可重入锁
下面有两段代码,都是表示锁都是重入锁。
package com.newDemo.controller.test;
public class threadDemo26 implements Runnable {
public synchronized void get() {
System.out.println("name:" + Thread.currentThread().getName() + " get();");
set();
}
public synchronized void set() {
System.out.println("name:" + Thread.currentThread().getName() + " set();");
}
public void run() {
get();
}
public static void main(String[] args) {
threadDemo26 ss = new threadDemo26();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
}
}
上面这个使用的就是synchronized重入锁
package com.newDemo.controller.test;
import java.util.concurrent.locks.ReentrantLock;
public class threadDemo27 extends Thread {
ReentrantLock lock = new ReentrantLock();
public void get() {
lock.lock();
System.out.println(Thread.currentThread().getId());
set();
lock.unlock();
}
public void set() {
lock.lock();
System.out.println(Thread.currentThread().getId());
lock.unlock();
}
@Override
public void run() {
get();
}
public static void main(String[] args) {
threadDemo27 ss = new threadDemo27();
new Thread(ss).start();
new Thread(ss).start();
new Thread(ss).start();
}
}
上面这个使用的就是ReentrantLock重入锁