Why can't Java constructors be synchronized?

前端 未结 9 1472
甜味超标
甜味超标 2020-11-29 18:20

According to the Java Language Specification, constructors cannot be marked synchronized because other threads cannot see the object being created until the thread creating

9条回答
  •  庸人自扰
    2020-11-29 19:07

    The following code can achieve the expected result for synchronized constructor.

    public class SynchronisedConstructor implements Runnable {
    
        private int myInt;
    
        /*synchronized*/ static {
            System.out.println("Within static block");
        }
    
        public SynchronisedConstructor(){
            super();
            synchronized(this){
                System.out.println("Within sync block in constructor");
                myInt = 3;
            }
        }
    
        @Override
        public void run() {
            print();
        }
    
        public synchronized void print() {
            System.out.println(Thread.currentThread().getName());
            System.out.println(myInt);
        }
    
        public static void main(String[] args) {
    
            SynchronisedConstructor sc = new SynchronisedConstructor();
    
            Thread t1 = new Thread(sc);
            t1.setName("t1");
            Thread t2 = new Thread(sc);
            t2.setName("t2");
    
            t1.start();
            t2.start();
        }
    }
    

提交回复
热议问题