假设我有以下代码片段,其中两个线程访问具有两个关键部分(同步语句)的相同方法.这些同步语句中的每一个都被赋予不同的锁定对象.代码如下:
public class MyWorker {
private Random random = new Random();
private Object lock1 = new Object();
private Object lock2 = new Object();
private List list1 = new ArrayList<>();
private List list2 = new ArrayList<>();
private void stageOne() {
synchronized (lock1) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
list1.add(random.nextInt(100));
}
}
private void stageTwo() {
synchronized (lock2) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
list2.add(random.nextInt(100));
}
}
private void process() {
for (int i=0; i<1000; i++) {
stageOne();
stageTwo();
}
}
void main() {
Thread t1 = new Thread(this::process);
Thread t2 = new Thread(this::process);
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
我的问题不是关于此代码中的错误或者它如何在java站点中执行.这段代码工作正常.我只是将它作为参考代码,以便回答的人有一个特定的场景来引用我想知道JVM如何在内部创建与此实例关联的监视器对象以及如何使用OpenJDK实现根据此场景在内部进行对象锁定.我期待一个低级别的解释.
我研究了这个主题几天,但找不到深入的解释.这些是我经历的一些调查结果:
>这个stackoverflow问题
Java lock concept how internally works?.
但我在答案中找不到彻底的解释.
> JLS 17.1提供有关监视器如何工作的语言说明
在高水平,但不是“内部发生”.
The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation.
In the Java virtual machine, every object and class is logically associated with a monitor. For objects, the associated monitor protects the object’s instance variables. For classes, the monitor protects the class’s class variables. If an object has no instance variables, or a class has no class variables, the associated monitor protects no data.
To implement the mutual exclusion capability of monitors, the Java virtual machine associates a lock (sometimes called a mutex) with each object and class. A lock is like a privilege that only one thread can “own” at any one time. Threads need not obtain a lock to access instance or class variables. If a thread does obtain a lock, however, no other thread can obtain a lock on the same data until the thread that owns the lock releases it. (To “lock an object” is to acquire the monitor associated with that object.)
> OpenJDK VM source code
我在指令集级别知道如何使用monitorenter和monitorexit操作码来管理同步语句.但我试图通过JVM源代码级别更深入地了解.但是我正在努力将OpenJDK源代码映射到我通过上面链接找到的高级解释,因为源代码中有许多内容.
那么熟悉OpenJDK源代码的人是否可以使用OpenJDK源代码解释以下与上述代码片段相关的问题?我认为ObjectMonitor,BasicLock,Synchronizer课程与此解释更相关.
>为哪个对象实例创建监视器对象?是MyWorker对象实例还是Object lock1或两者兼而有之?因为JSL和Bill Vennams的解释描述了每个对象都与监视器相关联.
>如果是MyWorker对象实例,那么如何为MyWorker对象实例创建监视器?
>如何为引用对象Object lock1创建锁定对象
我们过去了
>实际监视器是如何被线程的锁定对象锁定的?