synchronized和ReentrantLock都是重入锁,那么什么是重入锁?它有什么作用呢?
public class test {
public static void main (String[] args) throws InterruptedException {
for (;;){
current current = new test().new current();
new Thread(current).start();
}
}
class current implements Runnable{
@Override
public void run () {
get();
}
public synchronized void get(){
System.out.println(Thread.currentThread().getName());
set();
}
private synchronized void set () {
System.out.println(Thread.currentThread().getName());
}
}
}
在这里我们发现get和set方法上都有synchronized关键字,对对象上锁.执行get方法后,对象获得一个锁,锁还未释放,就进入set方法,再次获得同一对象上的锁.这个锁就是重入锁,每次获得相同的锁,就对锁计数+1,释放锁计数-1.当锁计数为0时,这个锁才被完全释放,可以被别的线程获取.