同步关键字内部实现 [英] Synchronized keyword internal implementation

查看:104
本文介绍了同步关键字内部实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入对象的同步方法后,JVM如何确保线程获得锁?

How does JVM make sure threads acquire a lock after entering synchronized method of an object?

推荐答案

广泛的问题:


JVM如何确保......?

How does the JVM make sure...?

JVM中的VM代表虚拟机。您的代码本身不会执行任何操作。当我们说你的代码运行时,我们真正的意思是,JVM 执行你的指令。它是按照JVM规范中规定的规则执行的。其中一条规则是JVM必须永远不要同时为同一个对象上的两个不同线程执行同步块。

The "VM" in "JVM" stands for "virtual machine." Your code doesn't do anything by itself. When we say, "your code runs", what we really mean is, the JVM executes your instructions. And it does so in accordance with the rules that are laid out in the JVM specification. One of the rules says that a JVM must never execute a synchronized block for two different threads on the same object at the same time.

但洋葱有很多层:典型的JVM使用本机线程(即操作系统提供的线程)来实现Java线程,它通常依赖于OS提供的互斥对象来同步线程。

But there are many layers to the onion: A typeical JVM uses native threads (i.e., threads provided by the operating system) to implement Java threads, and it typically relies on mutex objects provided by the OS to synchronize the threads.

更深入的是,JVM和操作系统都没有真正做任何事情:它是计算机硬件执行操作系统的指令和真正使用的JVM事情发生了。

Going deeper still, neither the JVM nor the operating system really does anything by itself: It's the computer hardware executing the instructions of the OS and the JVM that really makes things happen.

同步如何运作?的完整答案。这是一本关于操作系统设计的书中的几章,还有一本关于计算机体系结构的书中的几章,以及计算机科学的一部分。要完全理解这一切,您至少需要知道:

The complete answer to "how does synchronization work?" is a couple of chapters from a book about operating system design, plus a couple of chapters from a book on computer architecture, plus a shot of computer science on the side. To fully understand it all, you'll at least need to know about:


  • 用户模式指令与特权模式指令 ,

  • 系统调用如何工作,

  • 操作系统调度程序如何执行上下文切换

  • 硬件同步原语,如比较和交换(CAS),测试和设置(TAS),加载链接/存储条件(LL / SC)

  • "user-mode instructions" vs. "priviliged mode instructions",
  • How system calls work,
  • How an operating system "scheduler" performs "Context Switches"
  • hardware synchronization primitives like "Compare and Swap (CAS)", "Test and Set (TAS)", "load-link/store-conditional (LL/SC)"

他们都是你可以在维基百科上查找的主题,但IMO,书籍更适合学习这种深度的主题。

They're all subjects that you can look up on Wikipedia, but IMO, books are better for learning a subject of that depth.

这篇关于同步关键字内部实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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