Two threads accessing the same AtomicInteger. One thread increments its value, the other decrements it. - Java Thread

Java examples for Thread:synchronized

Description

Two threads accessing the same AtomicInteger. One thread increments its value, the other decrements it.

Demo Code


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class RunnableObject implements Runnable {

    private int id;
    private AtomicInteger atomicIntegerCounter;

    public RunnableObject(int id, AtomicInteger atomicIntegerCounter) {
        this.id = id;
        this.atomicIntegerCounter = atomicIntegerCounter;
    }//from  w  w  w  .j a  v  a  2 s  . c  o  m

    @Override
    public void run() {
        if (this.id % 2 == 1) {
            System.out.println("Incrementing atomicIntegerCounter from RunnableObject " + this.id + " to value " + atomicIntegerCounter.incrementAndGet());
        } else {
            System.out.println("Decrementing atomicIntegerCounter from RunnableObject " + this.id + " to value " + atomicIntegerCounter.decrementAndGet());
        }
    }
}

public class AtomicCounterExample {

    public static void main(String[] args) {

        AtomicInteger atomicIntegerCounter = new AtomicInteger(0);

        RunnableObject object1 = new RunnableObject(1, atomicIntegerCounter);
        RunnableObject object2 = new RunnableObject(2, atomicIntegerCounter);

        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);

        executorService.scheduleAtFixedRate(object1, 1, 1, TimeUnit.SECONDS);
        executorService.scheduleAtFixedRate(object2, 2, 2, TimeUnit.SECONDS);

        // stop it when you're done!
    }
}

Related Tutorials