First is incorrect because. See below program
class Test{
private int x;
private int y;
public void setX(int i){ x=i;}
public void setY(int i){y=i;}
public synchronized void setXY(int i){
setX(i);
setY(i);
}
public synchronized boolean check(){
return x!=y;
}
}
public class another implements Runnable
{
public void run()
{
Test ob=new Test();
System.out.println(ob.check()+ " "+Thread.currentThread().getName());
}
public static void main(
String ar[])
{
another Obj=new another();
Thread t1=new Thread(Obj,"one");
Thread t2=new Thread(Obj,"two");
Thread t3=new Thread(Obj,"three");
t1.start();
t2.start();
t3.start();
}
};
Second is correct because
class Test{
private int x;
private int y;
public void setX(int i){ x=i;}
public void setY(int i){y=i;}
public synchronized void setXY(int i){
setX(i);
setY(i);
}
public synchronized boolean check(){
return x!=y;
}
}
public class another implements Runnable
{
public void run()
{
Test ob=new Test();
ob.setX(1);
ob.setY(2);
System.out.println(ob.check()+ " "+Thread.currentThread().getName());
}
public static void main(String ar[])
{
another Obj=new another();
Thread t1=new Thread(Obj,"one");
Thread t2=new Thread(Obj,"two");
Thread t3=new Thread(Obj,"three");
t1.start();
t2.start();
t3.start();
}
};
Vilish