在Java中的静态块中创建线程时导致死锁 [英] Deadlock caused while creating a Thread in a static block in Java

查看:111
本文介绍了在Java中的静态块中创建线程时导致死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是试图在Java中的 static 块中创建一个线程,导致发生死锁。代码段如下。

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.
    }
}






它只是在控制台上显示检测到死锁并挂起。我想发生死锁的原因可能是在 main()方法之前首先加载 static 块被调用。你能在上面的代码片段中看到死锁的确切原因吗?


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?

推荐答案

为了让线程能够设置静态值,必须加载类。为了加载类,线程必须结束(以便静态块完成)。这可能就是你陷入僵局的原因。

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.

这篇关于在Java中的静态块中创建线程时导致死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆