gpt4 book ai didi

java - 对象级锁定是线程安全的吗?

转载 作者:行者123 更新时间:2023-12-03 12:48:43 24 4
gpt4 key购买 nike

我已经在对象级别实现了锁定以访问设备:

private static Object device_locker_ = new Object();

public Device getDevice() {
synchronized (device_locker_) {
return device_;
}
}

在这种情况下,不同的线程可以使用设备,通过getDevice()调用不同的方法吗?示例:

getDevice().getDeviceInfo()
getDevice().changePIN()
getDevice().doSomething()

所有线程都使用定义了 getDevice () 方法的类的一个实例。

在这种情况下是否可以保证只有一个线程可以与设备一起工作?

最佳答案

Can different threads in this case work with the device, callingdifferent methods through getDevice()? Examples:

getDevice().getDeviceInfo()
getDevice().changePIN()
getDevice().doSomething()

没有。不同的线程无法安全地使用 getDevice() 返回的同一实例,因为(基于我假设的方法名称) 返回的实例的内容>getDevice() 正在这些方法中进行修改(例如, changePIN())。

这个:

public Device getDevice() {
synchronized (device_locker_) {
// This is the safe zone
}
}

only 保证只有一个持有锁 device_locker_ 的线程可以访问 synchronized(device_locker_ ) 子句中的代码。如果将对象泄漏到外部,则该对象超出了 Synchronized 子句的范围,因此可以由多线程以非线程安全的方式访问。就像当你在家时,你的屋顶可以保护你免受雨淋一样,但如果你走到外面,那么你就在自己的房子里了。

All threads work with one instance of the class in which the getDevice() method is defined.

Is it guaranteed in this case that only one thread can work with thedevice?

这并不重要,只要 getDevice 返回在线程之间共享的相同对象内存引用,如果没有采取适当的措施,就存在竞争条件和数据竞争的风险采取(例如,确保对共享资源的访问互斥)。

关于java - 对象级锁定是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66211781/

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