52ky 发表于 2022-6-16 13:48:06

深入理解 Java 内存模型_InfoQ.pdf

在并发编程中,我们需要处理两个关键问题:线程之间如何通信以及线程之间如何同步(这里的线程是指并发执行的活动实体)。通信是指线程交换信息的机制。在命令式编程中,线程之间有两种通信机制:共享内存和消息传递。在共享内存并发模型中,程序的公共状态在线程之间共享,线程通过读写内存中的公共状态进行隐式通信。在消息传递的并发模型中,线程之间没有共同的状态,线程必须通过显式发送消息来显式通信。
同步是指程序用来控制不同线程之间操作发生的相对顺序的机制。在共享内存并发模型中,同步是显式完成的。程序员必须明确指定一个方法或一段代码需要在线程之间互斥地执行。在消息传递的并发模型中,同步是隐含的,因为消息的发送必须在消息的接收之前。
Java的并发采用共享内存模型。 Java线程之间的通信总是隐式的,整个通信过程对程序员来说是完全透明的。如果编写多线程程序的 Java 程序员不了解隐式线程间通信是如何工作的,那么很可能会遇到各种奇怪的内存可见性问题。

(In concurrent programming, we need to deal with two key issues: how to communicate between threads and how to synchronize between threads (threads here refer to concurrent execution of active entities). Communication refers to the mechanism by which threads exchange information. In imperative programming, there are two communication mechanisms between threads: shared memory and message passing. In the shared memory concurrency model, the common state of programs is shared among threads, and threads communicate implicitly by reading and writing the common state in memory. In the concurrency model of message passing, there is no common state between threads. Threads must communicate explicitly by explicitly sending messages.
Synchronization is a mechanism used by programs to control the relative order of operations between different threads. In the shared memory concurrency model, synchronization is done explicitly. The programmer must explicitly specify that a method or piece of code needs to be mutually exclusive between threads. In the concurrency model of messaging, synchronization is implicit because the message must be sent before it is received.
Java concurrency adopts the shared memory model. The communication between Java threads is always implicit, and the whole communication process is completely transparent to programmers. If Java programmers writing multithreaded programs do not understand how implicit inter thread communication works, they are likely to encounter various strange memory visibility problems.)




页: [1]
查看完整版本: 深入理解 Java 内存模型_InfoQ.pdf