jvm - Java new 對象是否是原子性的?
問題描述
public static void main(Sting args[]){ Object a=null; new Thread(){ a=new xxx() }.start(); new Thread(){ a=new xxx() }.start();}
想問,xxx()方法里有復雜的對象初始化邏輯,new關鍵字創建對象,是原子性的嗎?如果不是,會不會就出現了對象初始化錯亂的問題?
問題解答
回答1:沒明白你的意思,如果我猜得不錯的話:
這完全取決于你的構造方法里面的具體的邏輯,畢竟代碼是人寫的。
public class Test { static class A{public A(){ try {SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd:hh:mm:ss:SS');System.out.println(sdf.format(new Date()) + '--begin --從線程' + Thread.currentThread().getName() + '中創建A');Thread.sleep(2000);System.out.println(sdf.format(new Date()) + '--end--從線程' + Thread.currentThread().getName() + '中創建A'); } catch (InterruptedException e) {e.printStackTrace(); }} }public static void main(String[] args) {new Thread(new Runnable(){ @Override public void run() {System.out.println('A is ' +new A()); } }).start();new Thread(new Runnable(){ @Override public void run() {System.out.println('A is ' +new A()); } }).start(); }}
輸出:
2017-06-16:11:46:43:780--begin --從線程Thread-1中創建A2017-06-16:11:46:43:780--begin --從線程Thread-0中創建A2017-06-16:11:46:45:786--end--從線程Thread-0中創建A2017-06-16:11:46:45:786--end--從線程Thread-1中創建AA is nwe.Test$A@1e6a629cA is nwe.Test$A@27fcb25d
另一個例子,構造器中包含同步塊,每一個線程都需要等待前面的線程執行完成后才能執行。
import java.text.*;import java.util.Date;public class Test { static class A{public A(){ try {synchronized (Test.class) { SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd:hh:mm:ss:SS'); System.out.println(sdf.format(new Date()) + '--begin --從線程' + Thread.currentThread().getName() + '中創建A'); Thread.sleep(2000); System.out.println(sdf.format(new Date()) + '--end--從線程' + Thread.currentThread().getName() + '中創建A');} } catch (InterruptedException e) {e.printStackTrace(); }} }public static void main(String[] args) {new Thread(new Runnable(){ @Override public void run() {System.out.println('A is ' +new A()); } }).start();new Thread(new Runnable(){ @Override public void run() {System.out.println('A is ' +new A()); } }).start(); }}
輸出:
2017-06-16:11:49:33:548--begin --從線程Thread-0中創建A2017-06-16:11:49:35:549--end--從線程Thread-0中創建AA is nwe.Test$A@717c3e102017-06-16:11:49:35:550--begin --從線程Thread-1中創建A2017-06-16:11:49:37:553--end--從線程Thread-1中創建AA is nwe.Test$A@27280786回答2:
建議參考線程安全的單例模式
回答3:不具有,比如構造方法中寫了多條邏輯,在執行構造方法時,是可以中斷的。
回答4:“原子性”這種描述太抽象,樓主提問的時候最好不要認為所有人對某個詞的認識都完全一樣。我只能說構造方法是線程安全的,對于每一個對象,構造方法只會被執行一次,只會被一個線程執行。
相關文章:
1. javascript - jquery怎么讓a標簽跳轉后保持tab的樣式2. javascript - vue中怎么使用原生js插件3. php多任務倒計時求助4. javascript - 小demo:請教怎么做出類似于水滴不斷擴張的效果?5. javascript - 請問下面代碼中的...是擴展運算符還是操作運算符?這樣寫是什么意思?6. css - autoprefixer沒有添加web-kit前綴7. css - 如何把一個視圖放在左浮動定位的視圖的上面?8. javascript - JS變量被清空9. python的正則怎么同時匹配兩個不同結果?10. javascript - axios請求回來的數據組件無法進行綁定渲染
