这两个代码块的行为是否相同?您可以假设从线程调用这些run方法。
public synchronized void run() {
System.out.println("A thread is running.");
}
或者
static Object syncObject = new Object();
public void run() {
synchronized(syncObject) {
System.out.println("A thread is running.");
}
}
答案 0 :(得分:6)
public synchronized void run()
{
System.out.println("A thread is running.");
}
相当于:
public void run()
{
synchronized(this) // lock on the the current instance
{
System.out.println("A thread is running.");
}
}
并提供您的信息:
public static synchronized void run()
{
System.out.println("A thread is running.");
}
相当于:
public void run()
{
synchronized(ClassName.class) // lock on the the current class (ClassName.class)
{
System.out.println("A thread is running.");
}
}
答案 1 :(得分:0)
不,正如你所说的那样没有区别,但是方法本来就是静态的,synchronized块会把封闭类的类对象作为锁。