We need to create a resource class as below:
Another thread class is as below:
Now, create the main test class, which is as below:
}
you will get the output as below:
if you will remove synchronized keyword before method, then you can see that our resource will be inconsistent and thread in not safe.
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);
}
}
public class B extends Thread
{
Printable p2;
public B(Printable p2)
{
this.p2 = p2;
}
public void run()
{
p2.myprintTable(5);
}
}
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();
}
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