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 - node.js promise沒用2. golang - 用IDE看docker源碼時的小問題3. c++ - 如何正確的使用QWebEngineView?4. yii2中restful配置好后在nginx下報404錯誤5. javascript - js 寫一個正則 提取文本中的數據6. 算法 - python 給定一個正整數a和一個包含任意個正整數的 列表 b,求所有<=a 的加法組合7. android 如何實現如圖中的鍵盤上的公式及edittext的內容展示呢8. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?9. php自學從哪里開始?10. 網站被黑,請教下大神,怎么對datebase.php內容加密。
