atomicクラスとhashmapの組み合わせ

10262 ワード

 
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;


/**
 *  hashmap   Atomic 
 *  hashmap key entryhashmap *  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