重入锁概念

重入锁概念,第1张

重入锁概念

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

 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5590712.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存