2009-12-16
public class TestMain {
public static void main(String args[]){
TestSynchronized r1 = new TestSynchronized();
TestSynchronized r2 = new TestSynchronized();
Thread t1 = new Thread(r1, "t1");
Thread t2 = new Thread(r1, "t2");
t1.start();
t2.start();
}
}
class TestSynchronized implements Runnable
{
private int j = 0;
public void run()
{
for(int i=0; i<3; i++)
{
Single.getInstance().printsth();
}
}
}
class Single{
private static Single instance;
private A a;
private Single() {
this.a = new A();
System.out.println("Called new Instance A Constructor Mathod");
}
public static Single getInstance(){
if(instance==null){
instance = new Single();
System.out.println("Called new Instance Single Constructor Mathod");
}
/*instance = new Single();
System.out.println("Called new Instance Single Constructor Mathod");*/
return instance;
}
public synchronized void printsth(){ // 假如不加synchronized 關鍵字的話。出來的i 值 將毫無規律。
int i = a.getI();
i++;
a.setI(i);
System.out.println(Thread.currentThread().getName()+": A reference is "+a.toString()+"and A.is is"+a.getI());
}
}
class A{
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
-------------------
下面的結果是用了同步關鍵字
Called new Instance A Constructor Mathod
Called new Instance Single Constructor Mathod
t2: A reference is test.A@10b30a7and A.is is1
t2: A reference is test.A@10b30a7and A.is is2
Called new Instance A Constructor Mathod
Called new Instance Single Constructor Mathod
t1: A reference is test.A@1a758cband A.is is1
t1: A reference is test.A@1a758cband A.is is2
t1: A reference is test.A@1a758cband A.is is3
t2: A reference is test.A@10b30a7and A.is is3
-------
下面的結果是沒有用同步關鍵字
“t1: A is A@d9f9c3 and A.i is 1
t2: A is A@d9f9c3 and A.i is 2
t1: A is A@d9f9c3 and A.i is 3
t2: A is A@d9f9c3 and A.i is 4
t1: A is A@d9f9c3 and A.i is 5
t2: A is A@d9f9c3 and A.i is 6”
每個Single 對象下面都有一個A 執行個體, 多線程t1 和 t2 到底訪問那個單態下面的A執行個體,不一定的。
------
t2 Called new Instance A Constructor Mathod and A is A@d9f9c3
t1 Called new Instance A Constructor Mathod and A is A@757aef
t2 Called new Instance Single Constructor Mathod and Single is Single@9cab16
t1 Called new Instance Single Constructor Mathod and Single is Single@1a46e30
t2: A reference is A@757aefand A.is is1
t1: A reference is A@757aefand A.is is2
t2: A reference is A@757aefand A.is is3
t1: A reference is A@757aefand A.is is4
t2: A reference is A@757aefand A.is is5
t1: A reference is A@757aefand A.is is6
從上面的程式可以看出來, A@d9f9c3 是在Single@9cab16 下面的, 而 A@757aef 是Single@1a46e30 下面的。
但是t2 和t1 缺選擇了一個A@757aef 這個對象。可以想象成這樣,兩個CPU (t1 和t2),記憶體裡兩個A對象的執行個體,兩片記憶體塊。
這兩個cpu 到底選擇哪個記憶體塊 不一定的。隨機的。 但是要向把A對象裡的I 值 線性順序的輸出的話,則需要加上同步關鍵字。