AtomicInteger

本文深入探讨了Java中AtomicInteger类在并发环境下的使用,通过具体实例展示了如何利用AtomicInteger进行线程安全的计数操作。代码示例中创建了100个线程,每个线程对AtomicInteger实例进行1000次递增操作,最终验证了其原子性和线程安全性。

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

package com.company.bingfa;

import java.util.concurrent.atomic.AtomicInteger;

class MyThread10 extends Thread{
    public static AtomicInteger n;

    MyThread10(AtomicInteger n){
        this.n = n;
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            n.getAndIncrement();
        }
    }
}

public class MyAtomicInteger {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger n = new AtomicInteger(0);
        Thread[] threads = new Thread[100];
        for (int i = 0; i < threads.length; i++) {
            threads[i] = new MyThread10(n);
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].start();
        }
        for (int i = 0; i < threads.length; i++) {
            threads[i].join();
        }

        System.out.println(MyThread10.n);
    }
}

 

### AtomicInteger 的线程安全用法示例 `AtomicInteger` 是 Java 提供的一个用于多线程环境下的原子操作类[^1]。它通过无锁机制(基于 CAS,Compare-And-Swap)来保证线程安全,而无需显式使用 `synchronized` 关键字。以下是关于 `AtomicInteger` 的基本用法和一个线程安全的示例。 #### 基本用法 `AtomicInteger` 提供了多种原子操作方法,例如 `getAndIncrement()`、`incrementAndGet()`、`compareAndSet()` 等。这些方法确保在多线程环境下对共享变量的操作是线程安全的。 以下是一个简单的例子,展示如何使用 `AtomicInteger` 来生成唯一的序列号: ```java import java.util.concurrent.atomic.AtomicInteger; public class Sequencer { private final AtomicInteger sequenceNumber = new AtomicInteger(0); public int next() { return sequenceNumber.getAndIncrement(); // 原子性地获取并递增 } public static void main(String[] args) { Sequencer sequencer = new Sequencer(); System.out.println(sequencer.next()); // 输出 0 System.out.println(sequencer.next()); // 输出 1 System.out.println(sequencer.next()); // 输出 2 } } ``` 在这个例子中,`getAndIncrement()` 方法以原子方式返回当前值并将其递增[^2]。 #### 多线程环境下的线程安全示例 为了演示 `AtomicInteger` 在多线程环境下的线程安全性,可以参考以下代码: ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class AtomicIntegerExample { private final AtomicInteger counter = new AtomicInteger(0); public void incrementCounter() { counter.incrementAndGet(); // 原子性地递增计数器 } public int getCounterValue() { return counter.get(); // 获取当前值 } public static void main(String[] args) throws InterruptedException { AtomicIntegerExample example = new AtomicIntegerExample(); ExecutorService executor = Executors.newFixedThreadPool(10); for (int i = 0; i < 1000; i++) { executor.submit(example::incrementCounter); } executor.shutdown(); executor.awaitTermination(1, TimeUnit.MINUTES); System.out.println("Final Counter Value: " + example.getCounterValue()); } } ``` 在这个例子中,多个线程同时调用 `incrementCounter()` 方法来递增共享的 `AtomicInteger` 变量。由于 `incrementAndGet()` 方法是原子操作,因此即使在高并发环境下,最终的结果也始终是正确的[^4]。 #### 注意事项 尽管 `AtomicInteger` 提供了线程安全的操作,但需要注意的是,仅当操作完全依赖于单个 `AtomicInteger` 实例时,才能保证线程安全。如果需要组合多个操作或与其他非原子变量交互,则可能需要额外的同步机制[^3]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值