public class T0501_TestSync implements Runnable {
Timer timer = new Timer(); public void run() {
timer.add(Thread.currentThread().getName());
} public static void main(String[] args) {
T0501_TestSync test = new T0501_TestSync();
Thread t1 = new Thread(test);
Thread t2 = new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}}class Timer {
private static int num = 0; public synchronized void add(String name) {
num++;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
System.out.println(name + ", 你是第" + num + "个使用timer的线程");

}
}因为没有加锁,这个程序的输出应该是
t1, 你是第2个使用timer的线程
t2, 你是第2个使用timer的线程
但是,实际情况是这样的
t1, 你是第1个使用timer的线程
t2, 你是第2个使用timer的线程
高手解惑,多谢!!!