栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

重入锁概念

重入锁概念

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

 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/585318.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号