1 public class Test_XCTB implements Runnable{
2 Timer timer = new Timer();
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 Test_XCTB test = new Test_XCTB();
6 Thread t1 = new Thread(test);
7 Thread t2 = new Thread(test);
8 t1.setName("t1");
9 t2.setName("t2");
10 t1.start(); t2.start();
11 }
12 public void run() { //因为Test_XCTB实现了Runnable接口,所以要重写run方法
13 timer.add(Thread.currentThread().getName());
14 }
15
16 }
17
18 class Timer{
19 private static int num = 0;
20 public void add(String neme) { //或者public synchronized void add(String neme)
21 synchronized(this) {
22 num++;
23 try {
24 Thread.sleep(1);//休眠1毫秒
25 } catch (InterruptedException e) {}
26
27 System.out.println("This is the " + num + "th");
28
29 }
30 }
31 }
32
33 /*
34 * 输出结果为:This is the 2th;This is the 2th;两个num居然一样,与期望的1th和2th不一样!
35 * 原因在于在执行t1的时候,num++变成1;但遇到了sleep方法,所以t1停止,执行t2;此时num++变成2;然后在执行输出语句。
36 * 但其实不加sleep语句也会遇到t1被打断而出现一样的结果。
37 * 解决方法是在num语句前加上synchronized(this){}方法,表示将当前线程锁定,num也随之被锁定。
38 * 还可以简便的在public void add(String neme)方法处加上synchronize,变成public synchronize void add。
39 */