Synchronzed method
If multiple threads may access a method concurrently and you want the method to be accessed one by one then you synchronize that full method.
Synchronized block
If multiple threads may access a resource (primitives or objects) or a code and you want the resource to be accessed one by one then you lock them using the synchronized block based on an object. Another
thread may access that piece of code only if the current thread releases the object.
ex
String s = new String("Hello ");
//somewhere in a method
synchronized(s)
{
s = Thread.currentThread.getName(); //1
System.out.print(s + " "); //2
}
And you start 3 threads Thread1, Thread2, Thread3, with the above block you can be sure that the three threads will execute the above block one by one. The output can be "Thread1 Thread2 Thread3" or which ever thread manages to get the lock. If there is no lock, an example scenario might be Thread1 running "1" and Thread2 running "2" but the output is "Thread1" even though thread2 executes "2".
Think of this more like a crown for a king.
There is only one crown (
object) but there can be many princes want to become a king (
thread). But only one prince can wear that crown and become the king (
object lock). And other princes can become the king only if the current king loses the crown (
object release).
Hope this helps. Chilax dude.