JAVA method synchronization

Written By:

Trilochan Tarai

SILAN Technology, BBSR

 

When a method is defined by the keyword synchronized, is known as method synchronization. Synchronized method is used to lock an object for any shared resource. When a thread invokes a synchronized method, it automatically acquires the lock for that object and releases it when the thread completes its task.

Let’s see an example for better clarity:

MethodSynchronizedExample.java

class Test

{

            synchronized void show(int n)

            {

                        for(int k=1;k<=5;k++)

                        {

                                    System.out.println(n * k);

                                    try{

                                                Thread.sleep(1000);

                                    }

                                    catch(Exception e)

                                    {

                                    }

                        }

            }

}

class MyThread1 extends Thread

{

            Test t;

            MyThread1(Test t)

            {

                        this.t=t;

            }

             public void run()

            {

                        t.show(2);

            }

}

class MyThread2 extends Thread

{

 

Test t;

            MyThread2(Test t)

            {

                        this.t=t;

            }

             public void run()

            {

                        t.show(3);

            }

}

class MethodSynchronizedExample

{

            public static void main(String[] args)

            {

                        Test ob=new Test();

                        MyThread1 obj1=new MyThread1(ob);

                        MyThread2 obj2=new MyThread2(ob);

 

                        obj1.start();

                        obj2.start();

              }

}

Output:

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment