1 public class ThreadTest
2 {
3 private int j;
4 public static void main(String[] args)
5 {
6 ThreadTest t = new ThreadTest();
7 Add add = t.new Add();
8 Sub sub = t.new Sub();
9
10 for(int i=0;i<2;i++)
11 {
12 Thread t1 = new Thread(add);
13 t1.start();
14 Thread t2 = new Thread(sub);
15 t2.start();
16 }
17 }
18
19 /*这里add方法和sub方法加synchronized关键字是因为当两个线程同时操作同一个变量时,
20 * 就算是简单的j++操作时,在系统底层也是通过多条机器语句来实现,所以在执行j++过程也是要耗费时间,
21 * 这时就有可能在执行j++的时候,另外一个线程H就会对j进行操作,因此另外一个线程H可能操作的可能就
22 * 不是最新的值了。因此要提供线程同步。
23 */
24 private synchronized void add()
25 {
26 j++;
27 System.out.println(Thread.currentThread().getName()+":"+j);
28 }
29
30 private synchronized void sub()
31 {
32 j--;
33 System.out.println(Thread.currentThread().getName()+":"+j);
34 }
35
36 class Add implements Runnable
37 {
38 public void run()
39 {
40 for(int i=0;i<100;i++)
41 {
42 add();
43 }
44 }
45 }
46
47 class Sub implements Runnable
48 {
49 public void run()
50 {
51 for(int i=0;i<100;i++)
52 {
53 sub();
54 }
55 }
56 }
57 }