zoukankan      html  css  js  c++  java
  • 死锁例子

    线程T1持有锁A,再去获取锁B,线程T2持有锁B,再去获取锁A,这时候线程T1获取不到锁B,线程T2获取不到锁A,就发生死锁了

    public class DeadLock {
    
        private static final Object lockA = new Object();
        private static final Object lockB = new Object();
    
        public static void main(String[] args) {
    
            new Thread(() -> {
                synchronized (lockA) {
                    System.out.println(Thread.currentThread().getName() + "获得锁A");
                    try {
                        Thread.sleep(2_000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lockB) {
                        System.out.println(Thread.currentThread().getName() + "获得锁B");
                    }
                }
            }, "【线程一】").start();
    
            new Thread(() -> {
                synchronized (lockB) {
                    System.out.println(Thread.currentThread().getName() + "获得锁B");
                    try {
                        Thread.sleep(2_000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (lockA) {
                        System.out.println(Thread.currentThread().getName() + "获得锁A");
                    }
                }
            }, "【线程二】").start();
    
        }
    
    }
  • 相关阅读:
    给网站添加图标: Font Awesome
    queue队列
    threading.Event
    信号量 semaphore
    rlock递归锁
    lock多线程锁
    threading
    BaseRequestHandler
    Socket网络编程
    文件传输 FTP
  • 原文地址:https://www.cnblogs.com/moris5013/p/10710839.html
Copyright © 2011-2022 走看看