问题见源代码注释:
class Timer {
Integer num =0;
//只是一个改变num 自增的方法
public void add(String name){
//下面两句,一个用num 当锁,一个用this 当锁,结果第一个不管用,并没有避免线程问题
// synchronized(num){//这句话不管用
  synchronized(this){  //改成这句则会出现理想结果
num++; try{
Thread.sleep(1);
}catch(InterruptedException e ){
                                        }
System.out.println(name+"是第"+num+"个访问时间对象的");
}
}
}public class TestSync implements Runnable{
Timer t = new Timer();
public void run(){
t.add(Thread.currentThread().getName());}
public static void main(String [] args){

System.out.println("理想结果:\nt1是第1个访问时间对象的\nt2是第2个访问时间对象的\n 实际结果:");
TestSync test= new TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}}