【发布时间】:2012-11-15 03:28:46
【问题描述】:
我一直对以下场景感到困惑
MyClass 只有一个对象,有两个线程 T1、T2。 现在一个线程说 T2 将能够使用具有唯一 MyClass 对象锁的同步方法 m1(),如果它试图访问 m1(),其他线程 T2 将被阻塞。
现在我的看法是,如果 T2 将尝试通过访问静态共享字段来访问静态同步方法 m2(),它将被阻塞,因为当前对象锁定在 T1 上,并且无法执行 m2(),如果有两个Myclass 的对象,然后 T2 线程将能够访问 m1()。我是对还是错?
class MyClass
{
public static int i = 5;
public synchronized void m1()
{
System.out.println(i); //uses static field i of MyClass
//T1 is executing this method
}
public static synchronized void m3()
{
//T2 will be able to call this method on same object lock while it is using
//static field i???
System.out.println(i);//uses static field i of MyClass
}
}
这很令人困惑,请帮助。提前致谢。
【问题讨论】:
标签: java synchronization