Synchronized Method :
In Java, when we create two or more thread in order to share some common Resources in a program, then they tried to override each other, due to which the result which we try to acheive is not obtained. So in order achieve common Result when two thread trying to use common Resource, we use synchronized method . This provide the lock to common Resource due to which no other Thread can access common Resource until it is in Use.
Lets See Result without Synchronized method.
1. Class A // common Resource
package com.tech;
public class A extends Thread{
public void show(String m) // No Synchroniztion
{
for(int i=1;i<10;i++)
{
System.out.println("[");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(m);
System.out.println("]");
}}
}
2. Class B
package com.tech;
public class B extends Thread{
A x;
B(A y)
{
this.x=y;
}
public void run()
{
x.show("Calling From B");
}
}
3. Class C
package com.tech;
public class C extends Thread {
A x;
C(A y)
{
this.x=y;
}
public void run()
{
x.show("Calling From C");
}
}
4.
package com.tech;
public class Demo {
public static void main(String args[])
{ A ob=new A(); // Only One Object
B x=new B(ob);
C y=new C(ob);
x.start();
y.start();
}
}
Output :
[
[
Calling From B
]
[
Calling From C
]
[
Calling From B
]
[
Calling From C
]
[
Calling From C
]
[
Calling From B
]
[
Calling From C
]
[
Calling From B
]
[
Calling From C
]
[
Calling From B
]
[
Calling From B
]
[
Calling From C
]
[
Calling From B
]
[
Calling From C
]
[
Calling From B
]
[
Calling From C
]
[
Calling From B
]
Calling From C
]
Now Lets see Result , After using Synchronized Method On Class A's method (Common Resorce)
1.Class A :
package com.tech;
public class A extends Thread{
synchronized void show(String m) // Synchronized Method
{
for(int i=1;i<10;i++)
{
System.out.println("[");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(m);
System.out.println("]");
}}
}
2. Class B
package com.tech;
public class B extends Thread{
A x;
B(A y)
{
this.x=y;
}
public void run()
{
x.show("Calling From B");
}
}
3. class C
package com.tech;
public class C extends Thread {
A x;
C(A y)
{
this.x=y;
}
public void run()
{
x.show("Calling From C");
}
}
4.
package com.tech;
public class Demo {
public static void main(String args[])
{ A ob=new A(); // Only one object
B x=new B(ob);
C y=new C(ob);
x.start();
y.start();
}
}
Output :
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From B
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
[
Calling From C
]
0 Comment(s)