Java中静态块的线程安全性

Java中静态块的线程安全性

本文介绍了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的一个实例,并且在第二个线程实例化SomeClass的第二个实例时正在初始化静态块中的值,静态块会发生什么?第二个线程是否忽略它,假设它已经初始化,即使第一个线程没有完成?或者是否会发生其他事情?

If a thread is instantiating an instance of SomeClass and is in the middle of initializing the values in the static block when a second thread instantiates a second instance of SomeClass, 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.

这在。

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

08-20 02:01