java public 與 private 的問題

2012-04-30 12:30 pm
public class JavaApplication1 {
public int i = 1;
private int j = 1; //public int j = 1;

public static void main(String[] args) {
new JavaApplication1().runThread();
}

public void runThread() {
new Thread(new Runnable() {

@Override
public void run() {
i+=i+=1;
j+=j+=1;
System.out.println("i = " + i);
System.out.println("j = " + j);
}

}).start();
}
}

以上的code在 netbeans run 的結果是:
i = 3
j = 4

但當我將 j 的屬性由 private 變成 public
輸出的結果是:
i = 3
j = 3

點解 j 的值會不同了 ????????

而在eclipse上 run 不論屬性是 private 還是 public
其結果都是
i = 3
j = 3

究竟那個結果才是正確 ?????????????

回答 (3)

2012-05-01 7:27 am
✔ 最佳答案
大家都正確
只是threading 問題
2012-05-01 8:20 am
public class outer{
public int i=1;
private int j=1;
public static void main(String[] args){
new outer().new inner().Test();
}
class inner{
void Test(){
i+=i+=1;
j+=j+=1;
System.out.println("i="+i);
System.out.println("j="+j);
}}}

不是threading問題, 已改成了不是多綫程
結果都是 i = 3, j = 4
2012-05-01 7:50 am
Threading? Really? I'm not so sure as the manipulation and printing both happens on the same thread, no race condition at all.
I'm more towards a faulty optimization performed by the bytecode compiler or JIT.


收錄日期: 2021-04-13 18:39:37
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20120430000051KK00111

檢視 Wayback Machine 備份