It is pretty easy to program several threads to carry out completely independent tasks. The real difficulty arises when threads have to interact in some way. One way that threads interact is by sharing resources. When two threads need access to the same resource, such as a variable or a window on the screen, some care must be taken that they don’t try to use the same resource at the same time.
This type of problem is called a race condition. This occurs when one thread in the middle of a multi-step operation, and another thread can change some value or condition that the first is depending upon.
To fix the problem of race conditions, there has to be some way for a thread to get exclusive access to a shared resource. This is not a vital thing to implement, but java provides a high-level and relatively easy-to-use approach to exclusive access. It’s done with synchronized methods and with the synchronized statement. These are used to protect shared resources by making sure that only one thread at a time will try to access the resource.Synchronization in java actually provides only mutual exclusion, which means that exclusive access to resource is only guaranteed if every thread that needs access to that resource uses synchronization.