package com.example.sync;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicExample {

	private AtomicInteger counter = new AtomicInteger(0);
	public void increment() {
		int newValue = counter.incrementAndGet();
		System.out.println(Thread.currentThread().getName() 
				+ " incremented counter to " + newValue);
	}
	public int getCounter() {
		return counter.get();
	}
	
	public static void main(String[] args) {
		AtomicExample atomicExample = new AtomicExample();
		AtomicWorker w1 = new AtomicWorker(atomicExample);
		AtomicWorker w2 = new AtomicWorker(atomicExample);
		w1.start();
		w2.start();
		try {
			w1.join();
			w2.join();
		} catch (InterruptedException ex) {}
		System.out.println("Final counter value: " + atomicExample.getCounter());
	}
}

class AtomicWorker extends Thread {
	private AtomicExample example;
	public AtomicWorker(AtomicExample example) {
		this.example = example;
	}
	@Override
	public void run() {
		for(int i = 0; i < 5; i++) {
			example.increment();
		}
	}
}