我有一个关于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