Friday 11 November 2016

Synchronization



     When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.
    Java uses the keyword synchronizedfor this purpose. While a thread is inside a synchronized method, all other threads that try to call it on the same instance have to wait.
     For example,
synchronized void update()
{
  ……..
  ……..
}
When a method is declared synchronized, Java creates a ‘monitor’ and hands it over to the thread that calls the method first time.
Ø It is also possible to mark a block of code as synchronized as shown below:
synchronized(lock-object)
{
    ……..
    ……..
}
Ø This may lead to the problem of deadlock.
Ø Example:
class Show
{
synchronized public void display(String s)
 {
System.out.print("Hello "+s);
try{
Thread.sleep(100);
   }
catch(Exception e){}
System.out.println(" Welcome");
 }
}
class A extends Thread
{
 Show s;
 String msg;
public A(String m,Showobj)
 {
  s=obj;
msg=m;
 }
public void run()
 {
s.display(msg);
 }
}
classThreadsyn
{
public static void main(String args[])
 {
  Show s=new Show();
  A a1= new A("Sayan",s);
  A a2= new A("Rohit",s);
  A a3= new A("Raju",s); 
a1.start();
a2.start();
a3.start();
 }
}
Output:
Hello Sayan Welcome
Hello Rohit Welcome
Hello Raju Welcome

No comments:
Write comments