1 package incre;
2
3 public class Incre {
4 public static void main(String[] args) {
5 class Count implements Runnable {
6 public int num;
7 @Override
8 public void run() {
9 //自增操作,非原子操作,线程不安全
10 // for (int i = 0; i < 10000; i++) {
11 // num++;
12 // }
13
14 //对代码进行同步,查看正确结果。
15 synchronized (this) {
16 for (int i = 0; i < 10000; i++) {
17 num++;
18 }
19 }
20 }
21
22 public int getNum(){
23 return num;
24 }
25 }
26
27 Count c = new Count();
28
29 //创建多个线程
30 final int THREAD_COUNT = 10;
31 Thread[] threadArray = new Thread[THREAD_COUNT];
32 for(int i = 0; i < threadArray.length; i++){
33 threadArray[i] = new Thread(c);
34 }
35
36 //启动多个线程
37 for(Thread t : threadArray){
38 t.start();
39 }
40
41 //等待这些线程结束
42 for(Thread t : threadArray){
43 try {
44 t.join();
45 } catch (InterruptedException e) {
46 e.printStackTrace();
47 }
48 }
49
50 //查看计数结果
51 System.out.println("计数结果:" + c.getNum());
52 }
53 }