久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

jvm - Java new 對象是否是原子性的?

瀏覽:97日期:2023-10-26 16:18:59

問題描述

public static void main(Sting args[]){ Object a=null; new Thread(){ a=new xxx() }.start(); new Thread(){ a=new xxx() }.start();}

想問,xxx()方法里有復雜的對象初始化邏輯,new關鍵字創(chuàng)建對象,是原子性的嗎?如果不是,會不會就出現了對象初始化錯亂的問題?

問題解答

回答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() + '中創(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

另一個例子,構造器中包含同步塊,每一個線程都需要等待前面的線程執(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:

不具有,比如構造方法中寫了多條邏輯,在執(zhí)行構造方法時,是可以中斷的。

回答4:

“原子性”這種描述太抽象,樓主提問的時候最好不要認為所有人對某個詞的認識都完全一樣。我只能說構造方法是線程安全的,對于每一個對象,構造方法只會被執(zhí)行一次,只會被一個線程執(zhí)行。

標簽: java
相關文章:
主站蜘蛛池模板: 醴陵市| 定西市| 霍州市| 特克斯县| 宜章县| 雅江县| 邻水| 大足县| 井研县| 开江县| 宝清县| 青海省| 宁城县| 民勤县| 剑阁县| 涿州市| 醴陵市| 香港| 丹棱县| 山东| 瑞安市| 永宁县| 诸暨市| 武陟县| 潮安县| 合阳县| 秦安县| 永登县| 高台县| 合山市| 大荔县| 郧西县| 安阳县| 岳西县| 诸暨市| 尖扎县| 光山县| 房产| 剑阁县| 密云县| 河源市|