I am trying to learn Multithreading techniques.
I tried to implement the synchronized behaviour to increment the counter.
I am using two variables one is AtomicInteger and another one with normal counter as a.
Issue I am facing is when I am printing the values in thread t3. I am getting different values each time although output expected should be 1000.
When I comment out the atomicIntegers.increment() method in t1 and t2 of AtomicInteger counter then I get the value of counter a as 1000. Even though I am using locks.
Can someone Help me in understanding this and how to increment both the counters in a synchronized way together.
public static void main(String args[]) throws InterruptedException {
AtomicIntegers atomicIntegers = new AtomicIntegers();
Thread t1= new Thread() {
@Override
public void run() {
for(int i =0; i<500; i++) {
// atomicIntegers.increment();
atomicIntegers.incrementA();
}
}
};
Thread t2= new Thread() {
@Override
public void run() {
for(int i =0; i<500; i++) {
// atomicIntegers.increment();
atomicIntegers.incrementA();
}
}
};
Thread t3= new Thread() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
// System.out.println(atomicIntegers.getAtomicInteger());
System.out.println(atomicIntegers.getA());
}
}
};
// t3.setPriority(2);
// t1.setPriority(1);
// t2.setPriority(3);
t1.start();
t2.start();
t3.start();
}
}
class AtomicIntegers extends Thread{
AtomicInteger atomicInteger = new AtomicInteger(0);
private int a =0;
public ReentrantLock lock = new ReentrantLock();
public void increment() {
atomicInteger.incrementAndGet();
}
public void incrementA() {
synchronized (lock) {
a++;
}
}
public int getAtomicInteger() {
return atomicInteger.get();
}
public int getA() {
synchronized (lock) {
return a;
}
}
}