我有一個關於java中同步的問題。在下面的Java程序中,我沒有得到任何輸出。但是,如果我從方法IFoo.s()中刪除同步語句,我會得到一些輸出。看起來IFoo.setP()和IFoo.s()方法是相互同步的。但'synchronized'只能防止兩個線程同時調用synchronized方法,對嗎?Java Synchronized同步所有同步的類之間的方法?
package com.example.relectiontest;
import java.awt.Point;
import java.util.Random;
public class Main {
public static void main(String[] args) throws Exception{
final IFoo f = new IFoo();
Runnable r = new Runnable() {
public void run() {
Random r = new Random();
int a = r.nextInt(5)+1;
for(int i=0;i<1000000;++i){
f.setP(a);
}
}
};
Runnable r2 = new Runnable() {
public void run() {
for(int i=0;i<1000000;++i){
f.s();
}
}
};
Thread T1 = new Thread(r, "T1");
Thread T2 = new Thread(r, "T2");
Thread T3 = new Thread(r2, "T3");
T3.start();
T1.start();
T2.start();
}
private static class IFoo{
private Point p = new Point();
public synchronized void setP(int a){
//System.out.println("p1 "+Thread.currentThread());
p.x = a;
p.y = p.x;
int x = p.x , y = p.y;
if(x != y)
System.out.println(Thread.currentThread()+"\t"+x+" "+y);
//System.out.println("p2 "+Thread.currentThread());
}
public synchronized void s(){
//System.out.println("s");
p.x = 0;
}
}
}
那麼,爲什麼我不能看到任何輸出?
問候
你知道你的'System.out'調用在'IFoo.s()'中被註釋掉了嗎? –
'synchronized'實例方法將所有*一起同步到同一個實例*。 – Holger