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 - 微信網頁開發從菜單進入頁面后,按返回鍵沒有關閉瀏覽器而是刷新當前頁面,求解決?2. mysql replace 死鎖3. android - 安卓做前端,PHP做后臺服務器 有什么需要注意的?4. mysql - ubuntu開啟3306端口失敗,有什么辦法可以解決?5. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?6. extra沒有加載出來7. python3.x - Python not 運算符的問題8. python - 數據與循環次數對應不上9. mysql - C#連接數據庫時一直這一句出問題int i = cmd.ExecuteNonQuery();10. python小白,關于函數問題
