Simple Deadlock Examples

后端 未结 28 2290
失恋的感觉
失恋的感觉 2020-11-30 16:28

I would like to explain threading deadlocks to newbies. I have seen many examples for deadlocks in the past, some using code and some using illustrations (like the famous 4

28条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 17:12

    If method1() and method2() both will be called by two or many threads, there is a good chance of deadlock because if thread 1 acquires lock on String object while executing method1() and thread 2 acquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further, which will never happen.

    public void method1() {
        synchronized (String.class) {
            System.out.println("Acquired lock on String.class object");
    
            synchronized (Integer.class) {
                System.out.println("Acquired lock on Integer.class object");
            }
        }
    }
    
    public void method2() {
        synchronized (Integer.class) {
            System.out.println("Acquired lock on Integer.class object");
    
            synchronized (String.class) {
                System.out.println("Acquired lock on String.class object");
            }
        }
    }
    

提交回复
热议问题