JUC 可重入锁(递归锁)

一、lock

package com.wt.lock;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadDemon01 {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        new Thread(()->{
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"外层");

                try {
                    lock.lock();
                    System.out.println(Thread.currentThread().getName()+"内层");
                } finally {
                    lock.unlock();
                }

            } finally {
                lock.unlock();
            }
        }, "AA").start();

        new Thread(()->{
            System.out.println("Hello World");
        },"BB").start();
    }
}

二、synchronized

package com.wt.sync;

public class ThreadDemon01 {
    public static void main(String[] args) {
        Object o = new Object();
        new Thread(()->{
            synchronized (o){
                System.out.println(Thread.currentThread().getName()+"外层");
                synchronized (o){
                    System.out.println(Thread.currentThread().getName()+"中层");
                    synchronized (o){
                        System.out.println(Thread.currentThread().getName()+"内层");
                    }
                }
            }
        }, "AA").start();
    }
}

 

posted @ 2025-05-31 09:54  市丸银  阅读(11)  评论(0)    收藏  举报