Whenever there is an application or program which tends to deal with two or more threads, has to deal with concurrency issues as well.
Concurrency issues are due to conflicts between two or more threads attempting to change state of same object. This might result into inaccurate results for other threads.
So to overcome this problem we use synchronize keyword before a block of code or method declaration.
After placing synchronized keyword as shown below , the JVM guarantees/ensures that if any thread is accessing synchronized block of code, no other thread will able to access the block of code till the first one is done with its modifications.
package com.hubberspot.multithreading; public class SynchronizedThreads{ private String name; // Using synchronized keyword over a method or // block of code makes it locked for thread public synchronized String getName() { return this.name; } public synchronized void setName(String name) { this.name= name; } public void displayName(){ System.out.println("The name is : " + name); } }