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關(guān)鍵字創(chuàng)建對象,是原子性的嗎?如果不是,會不會就出現(xiàn)了對象初始化錯亂的問題?
問題解答
回答1:沒明白你的意思,如果我猜得不錯的話:
這完全取決于你的構(gòu)造方法里面的具體的邏輯,畢竟代碼是人寫的。
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() + '中創(chuàng)建A');Thread.sleep(2000);System.out.println(sdf.format(new Date()) + '--end--從線程' + Thread.currentThread().getName() + '中創(chuàng)建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中創(chuàng)建A2017-06-16:11:46:43:780--begin --從線程Thread-0中創(chuàng)建A2017-06-16:11:46:45:786--end--從線程Thread-0中創(chuàng)建A2017-06-16:11:46:45:786--end--從線程Thread-1中創(chuàng)建AA is nwe.Test$A@1e6a629cA is nwe.Test$A@27fcb25d
另一個例子,構(gòu)造器中包含同步塊,每一個線程都需要等待前面的線程執(zhí)行完成后才能執(zhí)行。
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() + '中創(chuàng)建A'); Thread.sleep(2000); System.out.println(sdf.format(new Date()) + '--end--從線程' + Thread.currentThread().getName() + '中創(chuàng)建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中創(chuàng)建A2017-06-16:11:49:35:549--end--從線程Thread-0中創(chuàng)建AA is nwe.Test$A@717c3e102017-06-16:11:49:35:550--begin --從線程Thread-1中創(chuàng)建A2017-06-16:11:49:37:553--end--從線程Thread-1中創(chuàng)建AA is nwe.Test$A@27280786回答2:
建議參考線程安全的單例模式
回答3:不具有,比如構(gòu)造方法中寫了多條邏輯,在執(zhí)行構(gòu)造方法時,是可以中斷的。
回答4:“原子性”這種描述太抽象,樓主提問的時候最好不要認為所有人對某個詞的認識都完全一樣。我只能說構(gòu)造方法是線程安全的,對于每一個對象,構(gòu)造方法只會被執(zhí)行一次,只會被一個線程執(zhí)行。
相關(guān)文章:
1. javascript - sublime快鍵鍵問題2. javascript - immutable配合react提升性能?3. css - 寫頁面遇到個布局問題,求大佬們幫解答,在線等,急!~4. javascript - nodejs關(guān)于進程間發(fā)送句柄的一點疑問5. Apache 已經(jīng)把網(wǎng)站根目錄的改為allow from all了,但是服務器還是不能訪問?6. 實現(xiàn)bing搜索工具urlAPI提交7. 配置Apache時,添加對PHP的支持時語法錯誤8. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化9. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?10. phpstudy8.1支持win11系統(tǒng)嗎?

網(wǎng)公網(wǎng)安備