多线程的死锁

作者: GuaKin_Huang | 来源:发表于2016-11-13 15:34 被阅读32次

    原因: 同时争夺同一资源导致死锁, 两个线程,彼此在等待对方占据的锁


    Thread1

    public class Thread1 extends Thread {
        Object o1;
        Object o2;
    
        public Thread1(Object o1, Object o2) {
            this.o1 = o1;
            this.o2 = o2;
        }
    
        @Override
        public void run() {
            synchronized (o1){
                System.out.println("进入线程 1 锁定对象 1");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2){
                    System.out.println("进入线程 1 锁定对象 2");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("进入线程 1 释放对象 2");
                }
                System.out.println("进入线程 1 释放对象 1");
            }
        }
    }
    

    Thread2

    public class Thread2 extends Thread {
        Object o1;
        Object o2;
    
        public Thread2(Object o1, Object o2) {
            this.o1 = o1;
            this.o2 = o2;
        }
    
        @Override
        public void run() {
            synchronized (o2){
                System.out.println("进入线程 2 锁定对象 2");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1){
                    System.out.println("进入线程 2 锁定对象 1");
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("进入线程 2 释放对象 1");
                }
                System.out.println("进入线程 2 释放对象 2");
            }
        }
    }
    

    测试

    public class Main {
        public static void main(String[] args) {
            Object o1 = new Object();
            Object o2 = new Object();
            Thread1 thread1 = new Thread1(o1, o2);
            Thread2 thread2 = new Thread2(o1, o2);
    
            thread1.start();
            thread2.start();
        }
    }
    

    结果

    result.gif

    相关文章

      网友评论

        本文标题:多线程的死锁

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