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

╄→尐↘猪︶ㄣ 提交于 2019-12-20 04:53:52

问题


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;

final public class Main
{
    static int value;

    static
    {
        final Thread t = new Thread()
        {
            @Override
            public void run()
            {
                value = 1;
            }
        };

        t.start();
        System.out.println("Deadlock detected");

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

    public static void main(String...args)
    {
        //Java stuff goes here.
    }
}

It just displays Deadlock detected on the console and hangs. I guess the reason for the deadlock to occur may be that the static block is loaded first before the main() method is invoked. Can you see the exact reason for the deadlock in the above code snippet?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/8610369/deadlock-caused-while-creating-a-thread-in-a-static-block-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!