1.
指的是同一个线程外层函数获得锁之后,内层递归函数仍然能获取该锁的代码,在同一个线程在外层方法获取锁的时候,在进入内层方法会自动获取锁。
也就是说,线程可以进入任何一个他已经拥有锁的所有同步代码块。
synchronized 和 ReentrantLock 都是可重入锁。
2.
synchrionized
public class Kechongru {
Lock lock = new ReentrantLock();
public synchronized void get(){
System.out.println(Thread.currentThread().getName()+"\t 运行了get()");
post();
}
public synchronized void post(){
System.out.println(Thread.currentThread().getName()+"\t 运行了post()");
}
public static void main(String[] args) throws InterruptedException {
Kechongru kechongru = new Kechongru();
System.out.println("验证synchronized:");
new Thread(()->{
kechongru.get();
},"t1").start();
new Thread(()->{
kechongru.get();
},"t2").start();
}
}
验证synchronized:
t1 运行了get()
t1 运行了post()
t2 运行了get()
t2 运行了post()
reentrantlock:
public class Kechongru {
Lock lock = new ReentrantLock();
public void eat(){
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+"\t 运行了eat()");
play();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void play() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+"\t 运行了play()");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
Kechongru kechongru = new Kechongru();
System.out.println("验证ReentrantLock:");
new Thread(()->{
kechongru.eat();
},"t3").start();
new Thread(()->{
kechongru.eat();
},"t4").start();
}
}
验证ReentrantLock:
t3 运行了eat()
t3 运行了play()
t4 运行了eat()
t4 运行了play()