java锁的应用

1、重量级锁sychronized

    public synchronized String testLock01() {
        // todo 业务逻辑
        return "test01";
    }

    public String testLock02() {
        synchronized (this) {
            System.out.println("true = " + true);
        }
        return "test02";
    }

 

2、reentrantLock

    final ReentrantLock reentrantLock = new ReentrantLock();

    public String test02() {
        reentrantLock.lock();
        System.out.println("销住的代码");
        reentrantLock.unlock();
        return "test02";
    }

    public void test03() {
        try {
            reentrantLock.lock();
            // 业务逻辑
        }finally {
            reentrantLock.unlock();
        }
    }

 

posted @ 2022-02-09 22:29  得好好活  阅读(62)  评论(0)    收藏  举报