Importance of Thread synchronization for multithreaded programs

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.
How to create a thread and start it running.
A thread in Java is represented by an object of the Thread class. Implementing threads is achieved in one of two ways:...
When should we use an event adapter class?
A listener’s class has to implement Listener interface which means all the methods of the interface must be defined in the class...
Component and container classes in Java
The Component class is found under java.awt package. The container class is the subclass of Component class...
Post your comment