import java.util.concurrent.ConcurrentHashMap;
import net.jcip.annotations.ThreadSafe;
import net.jcip.annotations.GuardedBy;
@ThreadSafe
public class Counter {
@GuardedBy("this")
private long count = 0;
public synchronized void increment() {
count++;
}
public synchronized long getCount() {
return count;
}
public static void main(String[] args) {
Counter counter = new Counter();
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
Thread threadA = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
map.put("A", i);
}
});
Thread threadB = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
map.put("B", i);
}
});
threadA.start();
threadB.start();
try {
threadA.join();
threadB.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Counter count: " + counter.getCount());
System.out.println("Map size: " + map.size());
}
}