classCase{//case one SynchronizedpublicsynchronizedvoidgetNum(){System.out.println(Thread.currentThread().getName()+"\t获取值。。");setNum();}publicsynchronizedvoidsetNum(){System.out.println("---"+Thread.currentThread().getName()+"\t存放值。。");}//case two ReentrantLockprivateLock lock =newReentrantLock();publicvoidget(){
lock.lock();System.out.println(Thread.currentThread().getName()+"\t获取值。。");set();//set是非静态方法,调用着默认是this,所以与get()的调用者一样,都是a
lock.unlock();}publicvoidset(){
lock.lock();System.out.println("###"+Thread.currentThread().getName()+"\t存放值。。");
lock.unlock();}}publicclassReEnterLockDemo{publicstaticvoidmain(String[] args){Case a =newCase();//case one SynchronizedSystem.out.println("----------case one----------");newThread(()->{
a.getNum();},"case one thread1").start();newThread(()->{
a.getNum();},"case one thread2").start();try{TimeUnit.SECONDS.sleep(2);}catch(InterruptedException e){
e.printStackTrace();}//case two ReentrantLockSystem.out.println("\n\n----------case two----------");newThread(()->{
a.get();},"case two thread1").start();newThread(()->{
a.get();},"case two thread2").start();}}/**
* 可重入锁(也叫做递归锁)
* 在同一个线程在外层方法获取锁的时候,在进入内层方法或会自动获取该锁。
* 也就是说,线程可以进入任何一个他已经拥有的锁的同步代码块。
*
* case one Synchronized就是一个典型的可重入锁
* ----------case one----------
* case one thread1 获取值。。 //thread1线程在外层方法获得锁的时候
* ---case one thread1 存放值。。 //thread1在进入内层方法会自动获取锁
* case one thread2 获取值。。
* ---case one thread2 存放值。。
*
* case two ReentrantLock也是一个可重入锁
* ----------case two----------
* case two thread1 获取值。。 //thread1线程在外层方法获得锁的时候
* ###case two thread1 存放值。。 //thread1在进入内层方法会自动获取锁
* case two thread2 获取值。。
* ###case two thread2 存放值。。