当前位置:网站首页>JVM - when multiple threads initialize the same class, only one thread is allowed to initialize

JVM - when multiple threads initialize the same class, only one thread is allowed to initialize

2022-07-05 01:42:00 A bowl of humble powder

One 、 problem

【 ask 】 What happens when multiple threads initialize a class at the same time

【 answer 】 Only one thread is allowed to perform initialization , Other threads will block .

        JVM Will guarantee a class of <clinit>() Methods are properly locked in a multithreaded environment , Sync .

Two 、 verification

【 Code 】

class Loader{
    static {
        //  Blocking method 
        System.out.println(" Initialization !!!");
        if (true){
            while (true){
                //System.out.println(" Blocking Lala ");
            }
        }
    }
}
public class CInit {
    public static void main(String[] args) {
        Runnable run = new Runnable(){

            public void run() {
                //  Create objects 
                System.out.println(Thread.currentThread().getName() + "《 Start creating objects 》");
                Loader loader = new Loader();
                System.out.println(Thread.currentThread().getName() + "《 End creating object 》");
            }
        };
        new Thread(run).start(); //  First thread 
        new Thread(run).start(); //  The second thread 
        new Thread(run).start(); //  The third thread 
    }
}

【 Console output 】

3、 ... and 、 Conclusion

        You can see from the results output from the console , Only one of the three threads has entered 【 initialization 】 in

【 Conclusion 】 If multiple threads initialize a class at the same time , There will only be one thread to initialize , Other threads are blocked .

原网站

版权声明
本文为[A bowl of humble powder]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202141019310771.html