thread12 - AtomXXX

package com.neutron.t12;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 讲解内容:AtomXXX
 *   因为++,--等操作不具备原子性,所以可以使用如下替代方式。
 *   AtomXXX类本身的方法都是原子性,但不能保证多个方法连续调用是原子性。
 *
 */
public class T12 {

    AtomicInteger count = new AtomicInteger(0);

    void mm() {
        for (int i = 0; i < 1000; i++) {
            count.incrementAndGet();  //代替count++,保证原子性操作

            // 注意下面则不构成原子性,因为在get时,线程a进行判断后,但是不执行下面代码
            // 线程b进行判断,执行完代码,此时代码是1000,然后线程a执行,此时结果是1001
            /*if (count.get() > 1000) {
                count.incrementAndGet();
            }*/
        }
    }

    /**
     预期结果:
        count: 10000
     运行结果:
        count: 10000
         开启10个线程,每个线程执行1000次,预期结果是10000
         1.使用 count.incrementAndGet();保证数据原子性操作
     */
    public static void main(String[] args) {
        T12 t11 = new T12();

        List<Thread> threads = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(t11::mm, "thread" + i));
        }

        threads.forEach(o -> o.start());

        threads.forEach((o) -> {
            try {
                o.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("count: " + t11.count);
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值