Accessing static variable from new thread inside static block causing program freeze

48 Views Asked by At

It seems that "static block + new thread + static variable" would cause program freeze?

public class HelloWorld{
    private static String str  = "Hi";
    
    static{
        Thread thread = new Thread(new Runnable(){
            public void run(){
                System.out.println(HelloWorld.str);
            }
        });
        
        thread.start();
        try{
            thread.join();
        }
        catch (InterruptedException e) {
                e.printStackTrace();
        }
        
        System.out.println("Static block end");
    }

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

The code above would cause program freeze.

While changing static variable to final static variable, like this

public class HelloWorld{
    private final static String str  = "Hi";
    
    static{
        Thread thread = new Thread(new Runnable(){
            public void run(){
                System.out.println(HelloWorld.str);
            }
        });
        
        thread.start();
        try{
            thread.join();
        }
        catch (InterruptedException e) {
                e.printStackTrace();
        }
        
        System.out.println("Static block end");
    }

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

or call from original thread, like this

public class HelloWorld{
    private static String str  = "Hi";
    static{
        System.out.println(HelloWorld.str);
        System.out.println("Static block end");   
    }

     public static void main(String []args){
        System.out.println("Hello World");
     }
}

would both work.

Not really sure why "static block + new thread + static variable" would cause program freeze?

0

There are 0 best solutions below