java Programs on Synchronization.

Synchronization

in this tutorial we are learn about synchronization in java. it is a capability to control access in multiple thread to any shared resources.java synchronization is better option to access the shared resources where we want to allow only one thread.

why synchronization is use?

synchronization is used to prevent thread interference and also prevent consistency problem.

//java program on synchronization

class first

 

{

public void display(String msg){

 

System.out.print("["+msg);

 

try

 

class second extends Thread

{

 

String msg;

 

first fobj;

 

second(first fp, String str)

{

 

fobj=fp;

 

msg=str;

 

start();

}

 

public void run()

 

{

 

synchronized(fobj)

 

{

fobj.display(msg);

 

}

 

}

 

}

Thread.sleep(5000);

 

}

 

catch(InterruptedException e)

 

{

e.printStackTrace();

 

}

System.out.println("]");

}

 

}

 

class sync

 

{

public static void main(String[] args)

 

{

 

first fnew=new first();

 

second ss=new second(fnew,"welcome"); second ss1=new second(fnew,"new"); second ss2=new second(fnew,"programmer");

 

}

 

}

 

Output:-

java Programs on Synchronization.

Post a Comment

0 Comments