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

相关