Thread Synchronization in java

So far we just know how to create new thread from main thread now lets see how we can do basic thread Synchronization in java. first lets discus problem that we will face if we do not Synchronize our threads if two or more threads are accessing same data. I have private variable count and in main method i am creating instance of Main class and invoking run method , like so
    private int count = 0;

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Thread Synchronization example code");
        Main m = new Main();
        m.run();

    }
very simple , now lets see that is it in run method
   public void run() throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 1500; i++) {
                    increment();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 1; i <= 1500; i++) {
                    increment();
                }
            }
        });

        // starting both threads
        t1.start();
        t2.start();

        // waiting for both threads to join with main thread
        t1.join();
        t2.join();

        System.out.println("Value  of Count is : " + count);
    }
as you can see i am creating two different threads t1 , t2 and in run method of both threads i am using for loop to call increment method 1500 times. and after that i am writing value of count variable to console and in increment method i am incrementing value of count like so
    public void increment() {
        count++;
    }
so in simple words i can say that in run methods i am increasing value of count variable 3000 times with two different threads. so we should also get value of count variable 3000 when we run this code but unfortunately it will give you different values not correct answer. this is the output that i get when i run this code multiple times
Run 1 
Thread Synchronization example code
Value  of Count is : 2998
BUILD SUCCESSFUL (total time: 0 seconds)

Run 2
Thread Synchronization example code
Value  of Count is : 2630
BUILD SUCCESSFUL (total time: 0 seconds)

Run 3 
Thread Synchronization example code
Value  of Count is : 2996
BUILD SUCCESSFUL (total time: 0 seconds)
in back end compiler expand this line count++; like this
        int temp; // 1
        temp = count ; // 2
        temp = temp + 1; // 3
        count = temp; // 4
lets say both threads t1 and t2 reads value of count 100 (line no 2) and while t1 increments its value by adding 1 ( line no 3 ) , t2 thread increment it and save it in original variable ( line no 4) so now value of count  is 101 because t1 reads 100 value it increment it and save back it count . so final value of count becomes 101 but it should be 102 :( i hope you guys understand the problem , we can solve this problem if we allow only 1 thread to enter in increment method at a time. this is called thread Synchronization in java , we can do this by using  Synchronized keyword like this
public synchronized void increment() {
        count++;
    }
or you can use Synchronized block as well
public  void increment() {
        synchronized(this){
            count++;
        }
    }
both does same job , i will talk about Synchronized block more in next article. this will solve our problem :)
Thread Synchronization example code
Value  of Count is : 3000
BUILD SUCCESSFUL (total time: 0 seconds)
here is the full code
/**
 *
 * @author Azeem Tariq
 */
public class Main {

    private int count = 0;

    public static void main(String[] args) throws InterruptedException {

        System.out.println("Thread Synchronization example code");
        Main m = new Main();
        m.run();

    }

    public  void increment() {
        synchronized(this){
            count++;
        }
    }

    public void run() throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 1; i <= 1500; i++) {
                    increment();
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                for (int i = 1; i <= 1500; i++) {
                    increment();
                }
            }
        });

        // starting both threads
        t1.start();
        t2.start();

        // waiting for both threads to join with main thread
        t1.join();
        t2.join();

        System.out.println("Value  of Count is : " + count);
    }

}

More useful resources

  1. Java  Thread Synchronization - TutorialsPoint
  2. Synchronizing threads in Java - JavaWorld
  3. Example Of Threading and Synchronization - ProgrammerInterview
  4. Synchronized block in java -  JavaPoint