码迷,mamicode.com
首页 > 其他好文 > 详细

i++操作非原子的验证代码

时间:2019-04-17 00:13:08      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:event   span   main   except   err   class   eve   syn   自增   

技术图片
 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 }
i++非原子操作验证代码

 

i++操作非原子的验证代码

标签:event   span   main   except   err   class   eve   syn   自增   

原文地址:https://www.cnblogs.com/mozq/p/10720952.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!