class Caller extends Thread
{
String s;
Caller(String s)
{
this.s=s;
}
void call(String msg)
{
synchronized (this)
{
System.out.print("["+msg);
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("]");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public void run()
{
call(s);
}
}
public class SynchronisedBlock {
public static void main(String[] args) {
Caller c=new Caller("hi");
Caller c1=new Caller("li");
Caller c2=new Caller("wi");
c.start();
c1.start();
c2.start();
}
}
public class SynchronisedBlock {
public static void main(String[] args) {
Caller c=new Caller("hi");
Caller c1=new Caller("li");
Caller c2=new Caller("wi");
c.start();
c1.start();
c2.start();
}
}
我想获得同步访问调用()使用同步块,但没有得到该功能。当我把call()方法在另一个类,然后我得到所需的功能,但不是在此代码中。我错过了什么?谁能告诉我为什么?提前Thanx。为什么我没有在我的代码中获得同步访问?
你正在'this'上同步,'this'每次调用每个'Caller'对象。你需要有一个公共的同步对象。 – SomeDude
@svasa非常感谢你。 – Ankit