gpt4 book ai didi

Java - 同步块(synchronized block)的工作方式与方法不同

转载 作者:行者123 更新时间:2023-12-02 21:59:29 25 4
gpt4 key购买 nike

我试图弄清楚同步块(synchronized block)和同步函数之间的区别到底是什么。这段代码工作得很好,因为它避免了关键部分的错误

class ThreadSynchronous extends Thread {
static int m_count = 0;
String s;

ThreadSynchronous(String s) {
this.s = s;
}

public void run() {
synchronized (getClass()) {
...
}
}
}

public class ThreadExample {
public static void main(String[] args) {
Thread t1 = new ThreadSynchronous("Thread1: ");
Thread t2 = new ThreadSynchronous("Thread2: ");
t1.start();
t2.start();

try{
t1.join();
t2.join();
} catch (InterruptedException e){
}
}
}

但是如果我使用 public synchronized void run() 来代替,它就不能同等/正常地工作。

最佳答案

根据 JLS 8.4.3.6. synchronized Methods :

A synchronized method acquires a monitor (§17.1) before it executes.

For a class (static) method, the monitor associated with the Class object for the method's class is used.

For an instance method, the monitor associated with this (the object for which the method was invoked) is used.

synchronized (getClass())阻止您在 Class 上同步对象,因此 ThreadSynchronous 的所有实例已连载。

当您创建实例方法synchronized ,您仅在该实例上同步(this 引用)。

关于Java - 同步块(synchronized block)的工作方式与方法不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50882629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com