美文网首页
线程同步中的死锁

线程同步中的死锁

作者: 鱿鱼炸酱面 | 来源:发表于2022-01-24 09:46 被阅读0次
    何为死锁

    多线程各自持有不同的锁,并互相试图获取对方已持有的锁,导致无限等待的状况,称为死锁。比如:

    public class DeadLock {
        public static void main(String[] args) {
            Object o1 = new ArrayList<>();
            Object o2 = new ArrayList<>();
            Thread t1 = new Thread(new MyRunnable1(o1, o2));
            Thread t2 = new Thread(new MyRunnable2(o1, o2));
            t1.start();
            t2.start();
        }
    }
    
    class MyRunnable1 implements Runnable {
    
        final Object o1;
        final Object o2;
    
        MyRunnable1(Object o1, Object o2) {
            this.o1 = o1;
            this.o2 = o2;
        }
    
        @Override
        public void run() {
            synchronized (o1) {
                System.out.println(Thread.currentThread().getName() + "已经获得o1的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("fsf");
                }
            }
        }
    
    }
    
    class MyRunnable2 implements Runnable {
    
        final Object o1;
        final Object o2;
    
        MyRunnable2(Object o1, Object o2) {
            this.o1 = o1;
            this.o2 = o2;
        }
    
        @Override
        public void run() {
            synchronized (o2) {
                System.out.println(Thread.currentThread().getName() + "已经获得o2的锁");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("fsf");
                }
            }
        }
    
    }
    
    避免死锁

    避免死锁的方法是线程获取锁的顺序要一致。

    相关文章

      网友评论

          本文标题:线程同步中的死锁

          本文链接:https://www.haomeiwen.com/subject/sgqbhrtx.html