synchronized (object reference expression) {
//code block
}
Example of synchronized block:class First
{
public synchronized void display(String msg)
{
System.out.print ("["+msg);
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println ("]");
}
}
class Second extends Thread
{
String msg;
First fobj;
Second (First fp,String str)
{
fobj = fp;
msg = str;
start();
}
public void run()
{
synchronized(fobj){ //synchronized block
fobj.display(msg);
}
}
}
public class SyncBlockDemo
{
public static void main (String[] args)
{
First fnew = new First();
Second ss = new Second(fnew, "welcome");
Second ss1 = new Second (fnew,"to");
Second ss2 = new Second(fnew, "dineshonjava.com");
}
}

Labels: multithreading