Why is thread synchronization important for multithreaded programs?
Threads share the same memory space, i.e., they can share resources. However, there are critical situations where it is desirable that only one thread at a time has access to a shared resource. For this Java provides synchronization to control access to shared resources. For the consistency of data Synchronization is used. Without synchronization it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to an error.
For example:public class MyStack
{
int idx=0;
char [ ] data= new char[6];
public void push (char c)
{
data [idx]=c; idx++;
}
public char pop ()
{
Idx--;
return data[idx];
}
}
In this program if two threads is sharing the data of this program. One thread is pushing data and the other is popping data off the stack. At this point the object is inconsistent. So to remove inconsistency synchronization of threads is used. For synchronization synchronized keyword is used. There are two ways of synchronization i.e. synchronized method and synchronized blocks.