atomic类与hashmap的组合

针对多线程位点提交问题
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, offsetInner> hashp = new HashMap<>();
    public static void main(String[]args){
        HashMap, 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
结果省略一部分

你可能感兴趣的:(日常)