The purpose of the synchronized statement (ref: here ) is to make sure that in a multi-threaded application, only one thread can access the critical data structure at a given time.
For example, if you allow two threads to simultaneously change the same data structure, the data structure will be corrupted, then you usually protect it with a lock.
In the real world, consider an analogue where a public toilet has a key hanging in a central place. Before you can use the toilet, you need a key not only to enter, but also a guarantee that no one else will try to enter the same toilet at the same time. They will have to wait until the key becomes available.
Here's how this lock design works.
The synchronized keyword parameter is the key in this case. You lock the key, do what you need to do, then you unlock the key so that others have access to it. If other threads try to lock the key while it is currently blocked by another thread, this thread will have to wait.
source share