问题描述
我创建了两个线程,并使用了一个称为该对象的静态和非静态方法的类的单个实例.理想情况下,需要使用类名调用静态方法,我也这样做了.
I created two threads and using a single instance of class called the static and non-static methods of that object. Ideally static methods need to be called using the class name and i did that too.
我在线程正在调用其方法的类的私有静态成员上同步静态和非静态方法.我注意到输出是同步的!
I synchronized both the static and non-static methods on a private static member of the class whose methods the threads are calling. I noticed that the output was synchronized!
我的问题是:
静态方法如果使用同步块同步它通常需要类实例,那么它是如何接受静态对象的!
Static methods if synchronized using a synchronized block it usually requires the class instance, then how did it accept a static object!
当调用静态方法的线程获取类级锁而调用非静态方法的线程获取对象级锁时,输出是如何同步的!
尽管我在基于对象的静态和非静态方法中都使用了同步块,但它确实不应该同步;还是静态对象上的同步块是特殊情况?
How was the output synchronized as threads calling static methods acquire the class level lock and threads calling non-static methods acquire object level lock!
Even though i have used synchronized block in both the static and non-static methods based on an object, it really shouldn't synchronize; or is it special case with synchronized blocks on static objects?
请告诉我.
以下是我写的代码:
public class StaticNonStaticSynch
{
public static void main(String[] args)
{
final StaticNonStaticTest staticNonStaticTest = new StaticNonStaticTest();
Runnable runnable1 = new Runnable()
{
@Override
public void run()
{
staticNonStaticTest.nonStaticMethod();
}
};
Runnable runnable2 = new Runnable()
{
@Override
public void run()
{
staticNonStaticTest.staticMethod();
}
};
Thread thread1 = new Thread(runnable1, "First Thread");
Thread thread2 = new Thread(runnable2, "Second Thread");
thread1.start();
thread2.start();
}
}
class StaticNonStaticTest
{
private static Object object = new Object();
void nonStaticMethod()
{
synchronized (object)
{
for(int i=0;i<500;i++)
{
System.out.println("Non - Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
}
}
static void staticMethod()
{
synchronized (object)
{
for(int i=0;i<500;i++)
{
System.out.println("Static method called by " + Thread.currentThread().getName() +" : = "+i);
}
}
}
}
推荐答案
在全球范围内,存在一个名为 StaticNonStaticTest.object
的实例.每当你同步那个东西时(不管来自哪里),你就是在同一个锁上同步.
Globally, there exists one instance of the thing called StaticNonStaticTest.object
. Whenever you synchronize on that thing (regardless where from), you are synchronizing on the same lock.
这篇关于静态和非静态方法的同步块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!