0

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();

}

}

3 Answers3

0

Because your code is in the loop .And balance is global data.

In the first loop ,you balance's value is 1 .

for (int i = 0; i < 50; i++) {

      increment();
      System.out.println(Thread.currentThread().getName() + " balance after increment is " + balance);
}

OUTPUT

//          i       balance
//  first   0          1
//  second  1          2
//  third   2          3
//  ...
KeLiuyue
  • 8,149
  • 4
  • 25
  • 42
0

Your increment method is synchronized but the balance variable is shared by the threads. After the first thread calls increment, before it can print balance, the other thread can call increment. Put the print statement inside increment method.

ssc327
  • 690
  • 1
  • 9
  • 19
0

Both threads share the same object. The only synchronized method increments i's value, but there is no guarantee for the order they'll take when printing the value neither for the state at which they will print it.

If you want each method to print its value after the increment, uncomment the sysout from the synchronized method and remove it from run().

If you expect all threads to finish before you print, you will need to use Thread.join().

Here's a quick example:

class TestSync implements Runnable {
    private int balance;

    public void run() {

        for(int i = 0; i < 50; i++){
            increment();
        }

    }

    private synchronized void increment() {

        int i = balance;
        balance = i + 1;
    }

    public void printBalance() ´{
        System.out.println("Balance: " + balance);
    }
}

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();

    try {
      System.out.println("Wait for threads to finish.");
      a.join();
      b.join();
    } catch (InterruptedException e) {
      System.out.println("Interruption waiting for threads to finish.");
    }
    a.printBalance(); // either method will print the same value.
}
Bernat
  • 492
  • 5
  • 13