A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

Example of Snychronization in mutlithreading in java

We need to create a resource class as below:

public class Printable
{
    public synchronized void myprintTable(int n)
    {
       System.out.println("Table of "+n);
       for(int i=1; i<=10; i++)
       {
           System.out.println(n*i);
       }
    }

}

Then, we need to create two thread class as below:

public class A extends Thread
{
   Printable p1;
   public A(Printable p1)
   {
       this.p1 = p1;
   }

   public void run()
   {
       p1.myprintTable(10);
   }
}

Another thread class is as below:

public class B extends Thread
{
       Printable p2;
    public B(Printable p2)
    {
       this.p2 = p2;
    }
    public void run()
       {
         
          p2.myprintTable(5);
       }
}

Now, create the main test class, which is as below:

public class Test
{
    public static void main(String[] args) {
       Printable pp=new Printable();
       A  t1 = new A(pp);
       B  t2 = new B(pp);
       t1.start();
       t2.start();
    }

}

you will get the output as below:

Table of 10
10
20
30
40
50
60
70
80
90
100
Table of 5
5
10
15
20
25
30
35
40
45
50

if you will remove synchronized keyword before method, then you can see that our resource will be inconsistent and thread in not safe. 

LEARN TUTORIALS

.

.