0
0

More than 1 year has passed since last update.

AtomicIntegerでsyncronized

Posted at

ValueをAtomicValueに差し替え
int numをAtomicInteger numに差し替え
AtomicInteger#addAndGet()を使うことにより
排他をしなくても読み替えから足しこみまでをatomicに行う

これは発生しない
1st thread num ref
2nd thread num ref
1st thread num + 100

こういったかんじ
1st thread num ref and +100
2nd thread num ref and +100

class Value{
    int num;
    public void add(int num) {
        this.num += num;
    }
    public int get() {
        return num;
    }
}
class AtomicValue extends Value {
    AtomicInteger num = new AtomicInteger(0);
    @Override
    public void add(int num) {
        this.num.addAndGet(num);
        System.out.println("atomicvalue add method");
    }   
    public int get() {
        System.out.println("atomicvalue get method");
        return num.intValue();
    }
}
class Task implements Runnable {
    Value v;
    Task(Value v) {
        this.v = v;
    }
    @Override
    public void run() {
        this.v.add(100);
    }
}
public class Outer {
    public static void main(String[] args) {
        Value v = new AtomicValue();
        ExecutorService e = Executors.newFixedThreadPool(4);
        e.submit(new Task(v));
        e.submit(new Task(v));
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println(v.get());
        e.shutdown();
    }
}
atomicvalue add method
atomicvalue add method
atomicvalue get method
200
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0