How this java code produces deadlock?

前端 未结 5 1734
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 10:23

i am going through oracle docs for deadlock.. i found this code

public class Deadlock {
    static class Friend {
        private final String name;
                 


        
5条回答
  •  忘掉有多难
    2020-12-21 11:08

    If you put a Thread.sleep(1000) after printing the first line and before making the call to bowBack, you should see a deadlock. This deadlock can happen anyway, it's will be rare.

    You have two threads and two locks being acquired is different orders. This can leave each thread holding one lock but unable to get the second lock. i.e. a deadlock.

    Note: threads take a lot of time to start which means the first thread can run to completion before the second one starts, so it is unlikely you will see the problem.


    Here is a puzzler for you. This creates a deadlock, can you see why?

    class A {
        static final int i;
        static {
            i = 128;
    
            Thread t = new Thread() {
                public void run() {
                    System.out.println("i=" + i);
                }
            };
            t.start();
            try {
               t.join();
            } catch (InterruptedException e) {
               Thread.currentThread().interrupt();
            }
        }
    

提交回复
热议问题