互斥-同步如何工作? [英] Mutual exclusion - How synchronized works?

查看:116
本文介绍了互斥-同步如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

answer 中所述,synchronized是使用 compareAndSwap 实现的,阻止算法.

As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.

  1. 在不使用wait()的情况下在synchronized上,线程状态是否设置为BLOCKED?

  1. On synchronized without using wait(), Does a thread state set to BLOCKED?

BLOCKED&中执行线程吗? WAITING状态会消耗CPU周期吗?

Does a thread in BLOCKED & WAITING state consume CPU cycles?

推荐答案

如答案中所述,同步是使用compareAndSwap实现的,compareAndSwap是一种非阻塞算法.

As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.

我认为您在误解该答案. synchronized当然不是通过Java级compareAndSwap调用实现的.它将由JVM中的解释器和JIT以本机代码实现.在幕后,它可能使用比较和交换指令,或者它可以使用其他指令(原子测试和设定以及原子交换也很常见-某些平台甚至没有CAS原语).

I think you are misreading that answer. synchronized is certainly not implemented with the Java-level compareAndSwap call. It will be implemented in native code by the interpreter and JIT in your JVM. Under the covers it might use the compare-and-swap instruction, or it may use something else (atomic test-and-set and atomic exchange are also common - and some platforms don't even have a CAS primitive).

这绝对不是非阻塞算法"-根据定义,synchronized实现了一种临界区,如果第二个线程试图进入另一个临界区,则它暗示了阻塞.在里面.

This is definitely not a "non-blocking algorithm" - by definition synchronized implements a type of critical section which implies blocking if a second thread tries to enter the critical section while another thread is inside it.

1)在不使用wait()的情况下进行同步时,线程状态是否设置为已阻塞"?

1) On synchronized without using wait(), Does a thread state set to BLOCKED?

是的,如果线程正在等待进入synchronized部分,则其状态将设置为BLOCKED.

Yes, if a thread is waiting to enter a synchronized section, its state is set to BLOCKED.

2)在BLOCKED&中是否有线程?等待状态会消耗CPU周期吗?

2) Does a thread in BLOCKED & WAITING state consume CPU cycles?

通常不,至少不是持续进行.进入和退出状态 1 会带来CPU成本,但是一旦线程被阻塞,它通常会保持不可运行状态,直到监视器空闲时它被唤醒为止,并且不会在这段时间内不要使用CPU资源.

Generally no, at least not in an ongoing manner. There is a CPU cost associated with entering and exiting the state1, but once the thread is blocked it is generally held in a non-runnable state until it is awoken when the monitor becomes free, and doesn't use CPU resources during that time.

1 这就是为什么良好的实现通常会在睡眠之前旋转"一点的原因,以防关键部分较短且保持线程可能很快退出-在这种情况下旋转避免了过渡到睡眠状态需要1000多个周期的开销(这涉及操作系统等).

1 Which is exactly why good implementations will generally "spin" a bit before going to sleep, in case the critical section is short and the holding thread may soon exit - spinning in this case avoids the 1000+ cycle overhead of making the transition to sleep (which involves the OS, etc).

这篇关于互斥-同步如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆