public class TestThreadSynchronized extends Thread{
 Time timer = new Time();
 public static void main(String[] args){
 
  TestThreadSynchronized t1 = new TestThreadSynchronized();
  TestThreadSynchronized t2 = new TestThreadSynchronized();
  //t1.setName("t1");
  //t2.setName("t2");
  t1.start();
  t2.start();
 
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}class Time{
Time(){}
private static int num = 0;
public synchronized static void add(String s){
num++;
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
System.out.println(s+" 你是第 "+num+" 个使用者");
}

为什么add()要用static 方法才可以实现 同步呢??不用静态方法就不行??哪位给解释一下

解决方案 »

  1.   

    static 是类被加载到内存的时候已经被初始化了,比创建这个类的实例还早,而且只有一片内存,但是实例可以有很多片
      

  2.   

    因为static方法synchronized JVM是在Time的CLass对象上加监视器
    所以即使有多个不同的Time对象,你的程序中的
     TestThreadSynchronized t1 = new TestThreadSynchronized();
     TestThreadSynchronized t2 = new TestThreadSynchronized();
    两个对象中有2个Time对象,
    调用add方法也是同步的
    如果是非静态的,则是在对象上加监视器,如果有两个Time对象,那么这两个对象的add方法是相互独立的
      

  3.   

    回去补基础吧... synchronized和static关键字的真正含义是什么.....