AtomicInteger实现多线程安全

本文介绍了一个使用Java实现的简单CAS锁并发测试程序。通过 AtomicInteger 实现乐观锁机制,多个线程竞争更新共享变量 number,最终验证并发安全性。该程序利用了循环等待来模拟锁的竞争过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CAS => 比较并交换,乐观锁

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

public class TestUnSafe {
    private static AtomicInteger lock = new AtomicInteger(1);
    private static int number = 0;

    public static void lock() {
        while (!lock.compareAndSet(1, 0)) { //获取锁失败一直死循环
        }
    }

    public static void unlock() {
        lock.compareAndSet(0, 1);
    }

    public static void test() {
        lock();
        for (int i = 0; i < 1000; i++) {
            number++;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        unlock();
    }

    public static void main(String[] args) throws InterruptedException {
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            threads.add(new Thread(() -> {
                test();
            }));
        }
        for (Thread thread : threads) {
            thread.start();
        }
        for (Thread thread : threads) {
            thread.join();
        }
        System.out.println(number);
    }



}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值