并发学习(九)— 多线程死锁

前言:

既然知道了多线程的同步怎么执行的,那么死锁通过synchronized怎么产生一个死锁呢~  之前阿里面试的时候面试官直接让我在电脑上敲出来~~只可惜我敲不出来= = !!直接在纸上写了个大概~,总之这个对于面试还是很重要的

@Slf4j
public class DeadLock {

    private static Object obj1 = new Object();
    private static Object obj2 = new Object();

    public static void main(String[] args) {

        new Thread(() -> {
            synchronized (obj1){
                log.info("thread1 get start lock1");
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    log.info("exception", e);
                }
                
                synchronized (obj2){
                    log.info("thread1 get start lock2");
                }
            }

            log.info("thread1 end");
        }).start();

        new Thread(() -> {
            synchronized (obj2){
                log.info("thread2 get start lock2");
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    log.info("exception", e);
                }

                synchronized (obj1){
                    log.info("thread2 get start lock1");
                }
            }
            log.info("thread2 end");
        }).start();
    }
}

你可能感兴趣的:(Java并发编程)