请教大虾线程问题,如下代码:
package com.test;
public class Timer {
private static int num = 0;
public synchronized void add(String name) {
num++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name + "是第" + num + "个访问的用户");
}
}
package com.test;
public class TestSync implements Runnable {
private Timer t = new Timer();
public void run() {
t.add(Thread.currentThread().getName());
}
}
package com.test;
public class test {
/**
* @param args
*/
public static void main(String[] args) {
Thread t1=new Thread(new TestSync());
Thread t2=new Thread(new TestSync());
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
输出的结果一直是:
t1是第2个访问的用户
t2是第2个访问的用户
疑问: 明明已经给 Timer类的add方法加了synchronized, 为么结果都是显示是第2个访问的用户
请求大神指点,小弟在此谢过!