K
K
kudim2017-10-29 20:26:11
Java
kudim, 2017-10-29 20:26:11

How to correctly change a shared variable from two threads?

Good evening!
There is a task like this:
"Write a short program in which two threads both increment a shared integer repeatedly, without proper synchronization, 1000 times, printing the result at the end of the program. Modify the program to use synchronized to ensure that increments on the shared variables are atomic." - Write a short program in which two threads simultaneously increment a shared variable, without synchronization, 1000 times, printing the result at the end of the program. Add synchronization to the program to ensure that the increments of the shared variable are atomic.
Wrote the following code:

public class Main {
  private static int element = 0;
  private static Object lock = new Object();

  public static void main(String[] args) {
    new Thread() {
      public void run() {
        synchronized (lock) {
          for (int i = 0; i < 1000; i++)
            element++;
        }
      }
    }.start();

    new Thread() {
      public void run() {
        synchronized (lock) {
          for (int i = 0; i < 1000; i++)
            element++;
        }
      }
    }.start();
    System.out.println(element);
  }
}

But 1000 is displayed. And actually the question. Where am I wrong? Why not 2000?
And if you remove the synchronization, then I also get 1000 at the output.
If the solution is fundamentally wrong, then I will be glad if you direct me in the right direction.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question