重入锁概念

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()

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值