Java中静态块的线程安全 [英] Thread safety of static blocks in Java

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

问题描述

假设我有一些 Java 代码:

Let's say I have some Java code:

public class SomeClass {
    static {
        private final double PI = 3.14;
        private final double SOME_CONSTANT = 5.76;
        private final double SOME_OTHER_CONSTANT = 756.33;
    }

  //rest of class
}

如果一个线程正在初始化 SomeClass 的 Class 对象,并且当第二个线程想要再次加载 SomeClass 的 Class 时,它正在初始化静态块中的值,怎么办发生在静态块上?假设它已经初始化,即使第一个线程没有完成,第二个线程是否会忽略它?还是发生了其他事情?

If a thread is initializing SomeClass's Class object and is in the middle of initializing the values in the static block when a second thread wants to load SomeClass's Class again, what happens to the static block? Does the second thread ignore it assuming it's already initialized even though the first thread is not done? Or does something else happen?

推荐答案

如果第一个线程没有完成 SomeClass 的初始化,第二个线程就会阻塞.

If the first thread hasn't finished initializing SomeClass, the second thread will block.

这在 第 12.4.2 节.

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

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