java原子操作cas_CAS 原子操作 AtomicInteger 使用

42bd13c6670274f0993c5c92419dc87e.png

实际上count++ 是三部操作:

a.线程获取内存中count变量的值

b.线程修改count变量的值:(0)+1

c.把count变量(0)+1的值赋值给count变量

而 AtomicInteger 的则是一个原子操作

案例代码:

package com.qimh.springbootfiledemo.thread;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.atomic.AtomicInteger;

/**

* @author

*/

public class SyncDemo {

// public int count;

public AtomicInteger count = new AtomicInteger();

public void testCount() throws InterruptedException {

for (int i=0;i < 100;i++){

Thread.sleep(10);

count.getAndIncrement();

// count++;

}

}

}

class MainTest{

public static void main(String[] agrs) throws InterruptedException {

SyncDemo syncDemo = new SyncDemo();

SyncDemo syncDemo2 = new SyncDemo();

// ExecutorService fixPoolThread = Executors.newFixedThreadPool(100);

// //提交是个任务

// for (int i = 0;i < 10;i++){

// fixPoolThread.execute(new Runnable() {

// @Override

// public void run() {

// try {

// syncDemo.testCount();

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

// }

// });

// }

// fixPoolThread.shutdown();

// System.out.println("count:" + syncDemo.count);

final CountDownLatch latch = new CountDownLatch(10);

for (int i = 0;i < 10;i++){

Thread thread1 = new Thread(new Runnable() {

@Override

public void run() {

try {

syncDemo.testCount();

} catch (InterruptedException e) {

e.printStackTrace();

}

latch.countDown();

}

});

thread1.start();

}

latch.await();

System.out.println("count:" + syncDemo.count);

// Thread thread2 = new Thread(new Runnable() {

// @Override

// public void run() {

// syncDemo.testCount();

// }

// });

// thread2.start();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值