使方法同步或将同步块添加到方法中有区别吗?

use*_*042 2 java multithreading synchronized

这两个代码块会表现得一样吗?您可以假设从线程调用这些运行方法.

public synchronized void run() {
    System.out.println("A thread is running.");
}
Run Code Online (Sandbox Code Playgroud)

要么

static Object syncObject = new Object();

public void run() {
    synchronized(syncObject) {
        System.out.println("A thread is running.");
    }
}
Run Code Online (Sandbox Code Playgroud)

Eng*_*uad 6

public synchronized void run()
{
    System.out.println("A thread is running.");
}
Run Code Online (Sandbox Code Playgroud)

等价于:

public void run()
{
    synchronized(this) // lock on the the current instance
    {
        System.out.println("A thread is running.");
    }
}
Run Code Online (Sandbox Code Playgroud)

并为您的信息:

public static synchronized void run()
{
    System.out.println("A thread is running.");
}
Run Code Online (Sandbox Code Playgroud)

等价于:

public void run()
{
    synchronized(ClassName.class) // lock on the the current class (ClassName.class)
    {
        System.out.println("A thread is running.");
    }
}
Run Code Online (Sandbox Code Playgroud)