例如,我有一个名为 increase
的方法。
public synchronized void increase() {
count++;
}
两个线程(T_1
和 T_2
)都执行此方法。我们知道count++
是一个由read
、modify
和write
组成的复合操作。如果T_1
先拿到锁,执行read
,此时是否可以中断T_1
(虽然T_2
可以'除了等待锁被释放之外,不需要做任何事情)?
来自Concurrency in Go by Katherine Cox-Buday ,它说:
When something is considered atomic, or to have the property of atomicity, this means that within the context that it is operating, it is indivisible, or uninterruptible.
我认为这意味着原子性真正不可中断。
但是从一个答案来看java - What does "atomic" mean in programming? - Stack Overflow ,它说:
"Atomic operation" means an operation that appears to be instantaneous from the perspective of all other threads. You don't need to worry about a partly complete operation when the guarantee applies.
我认为这意味着原子性是几乎不可中断(它可以被中断,但从所有其他线程的角度来看,它似乎不能被中断。)。
那么,哪一个是正确的呢?
最佳答案
有人指出,现在有一种方法可以让您的程序理解其中的差异。但是操作系统级别的线程调度程序可以自由地挂起一个线程并恢复另一个线程。
例如,如果在 synchronized
方法中,您正在执行一些阻塞 I/O(例如读取用户输入或从套接字读取),调度程序可以检测到它并暂停持有锁但在 I/O 上被阻塞的线程,并且尝试恢复任何其他线程(甚至可能是也在等待同一锁的线程)。
关于java - 原子性真的是不可中断的还是几乎不可中断的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59402376/