Java – Thread Synchronization

Thread Synchronization:

  • Synchronization is the concept of allowing thread sequentially when multiple threads trying to access the resource.
  • We implement synchronization using ‘synchronized’ keyword.
  • We can synchronize either Block or Method.

Program: Consider a method increase the value of x by 1 and when multiple threads are trying to invoke the method concurrently, we get odd results. Hence we need to synchronize the value() method.

class Modify
{
            static int x;
            synchronized static void value()
            {
                        x=x+1;
            }
}
class First extends Thread
{
            public void run()
            {
                        for (int i=1 ; i<=100000 ; i++)
                        {
                                    Modify.value();
                        }
            }
}
class Second extends Thread
{
            public void run()
            {
                        for (int i=1 ; i<=100000 ; i++)
                        {
                                    Modify.value();
                        }
            }
}
class Synchronization
{
            public static void main(String[] args)
            {
                        First t1 = new First();
                        Second t2 = new Second();
                        t1.start();
                        t2.start();
                        try
                        {
                                    t1.join();
                                    t2.join();
                        }
                        catch(Exception e){}
                        System.out.println(“Final x value : ” + Modify.x);
            }
}
Scroll to Top