In the below code after a thread runs the increment method it prints value 2 to the console.Shouldn't the value be 1 since the method increments it with 1?
class TestSync implements Runnable {
private int balance;
public void run() {
for(int i = 0; i < 50; i++){
increment();
System.out.println(Thread.currentThread().getName() + " balance after increment is " +balance);
}
}
private synchronized void increment() {
int i = balance;
balance = i + 1;
// System.out.println(balance);
}
}
public class TestSyncTest {
public static void main(String[] args) {
TestSync job = new TestSync();
Thread a = new Thread(job);
Thread b = new Thread(job);
a.setName("Thread A");
b.setName("Thread B");
a.start();
b.start();
}
}