Deadlock caused while creating a Thread in a static block in Java

后端 未结 3 510
既然无缘
既然无缘 2021-01-23 16:07

I was just trying to create a Thread in a static block in Java that caused a deadlock to occur. The code snippet is as follows.

package deadlock;

f         


        
相关标签:
3条回答
  • 2021-01-23 16:28

    Technically, you don't call this a deadlock. "Deadlock" implies that there is a monitor contention of some sort.

    What you are doing has the same effect as calling

    synchronized (Main.class) {
        try {
            Main.class.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    

    as the first thing in your main method. You are in a wait state from which you are never woken up.

    0 讨论(0)
  • 2021-01-23 16:42

    In order for the thread to be able to set the static value, the class must be loaded. In order for the class to be loaded, the thread must end (so that the static block completes). That's probably why you have a deadlock.

    0 讨论(0)
  • 2021-01-23 16:45

    if you comment out

        try
        {
            t.join();
        }
        catch (InterruptedException e)
        {
            System.out.println(e.getMessage());
        }
    

    deadlock will not occur...Your thread will run after class load.

    0 讨论(0)
提交回复
热议问题