atomic类与hashmap的组合

本文通过一个示例展示了在多线程环境下,如何利用Atomic类(AtomicBoolean与AtomicLong)与HashMap结合,实现对HashMap中特定Entry的并发修改。通过不加锁的方式,在HashMap的读取操作中,利用Atomic类的原子性特性确保了并发安全性,避免了数据竞争问题。

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

针对多线程位点提交问题
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;


/**
 * 测试hashmap Atomic类的组合
 * 在获取hashmapkey entry时不加锁  (hashmap无锁)
 * entry value中使用原子类 atomic 来控制并发
 * 以下示例 用两个线程来操作对hashmap中的同一个entry进行修改,操作都是依次进行 没有出现并发交替问题
 */
public class multiProcess implements Runnable {
    String name ;
    public multiProcess(String name){
        this.name = name;
    }
    static class offsetInner{
        public offsetInner(int offset){
            this.offset = new AtomicLong(offset);
            this.flag = new AtomicBoolean(false);
        }
        AtomicLong offset;
        AtomicBoolean flag = new AtomicBoolean(false);
    }

    static HashMap<Integer, offsetInner> hashp = new HashMap<>();
    public static void main(String[]args){
        HashMap<Integer, offsetInner> map = new HashMap<>();
        offsetInner offsetinner = new offsetInner(100);


        hashp.put(1,new offsetInner(100));
        hashp.put(2,new offsetInner(100));
        Thread t1 = new Thread(new multiProcess("thread1"));
        Thread t2 = new Thread(new multiProcess("thread2"));
        Thread t3 = new Thread(new multiProcess("thread3"));
        Thread t4 = new Thread(new multiProcess("thread4"));
        Thread t5 = new Thread(new multiProcess("thread5"));

        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
    public void run()  {
        int i =10;
        while(i>0) {
            //System.out.println("aaaaaaa");
            System.out.println(hashp.get(1).flag);

            if (hashp.get(1).flag.compareAndSet(false, true)) {
                hashp.get(1).offset.getAndIncrement();
                System.out.println(name +": " +hashp.get(1).offset);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            hashp.get(1).flag.set(false);
            i--;
        }
    }
}
false
thread1: 101
true
false
thread2: 102
true
false
thread3: 103
true
false
thread4: 104
true
false
thread5: 105
false
thread1: 106
false
thread2: 107
false
thread3: 108
false
thread4: 109
false
thread5: 110
结果省略一部分
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值