返回
深入剖析 Java 多线程:objectMonitor 源码解读(三)
后端
2023-11-01 03:25:45
认识monitor管程
监视器管程(Monitor)是一种同步机制,它允许多个线程同时访问共享数据,而不会发生数据损坏。Monitor 管程由两个基本操作组成:enter 和 exit。enter 操作允许线程进入管程,而 exit 操作允许线程离开管程。
objectMonitor 源码解析
ObjectMonitor 是 Java 中的一个类,它实现了监视器管程。ObjectMonitor 类提供了 wait、notify 和 notifyAll 方法,这些方法允许线程在对象上等待、通知和唤醒其他线程。
public class ObjectMonitor {
private boolean entered;
public synchronized void enter() {
while (entered) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
entered = true;
}
public synchronized void exit() {
entered = false;
notifyAll();
}
public synchronized void wait() {
while (entered) {
try {
wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public synchronized void notify() {
notifyAll();
}
public synchronized void notifyAll() {
notifyAll();
}
}
synchronized 的底层实现原理
synchronized 关键字用于将方法或代码块标记为同步的,它可以保证在同一时刻只有一个线程执行该方法或代码块。synchronized 关键字的底层实现原理是通过对象监视器(Object Monitor)来实现的。
wait/notify 机制的源码解析
wait、notify 和 notifyAll 方法是 Object 类中的方法,它们允许线程在对象上等待、通知和唤醒其他线程。
public final void wait() throws InterruptedException {
checkSync();
wait(0);
}
public final void wait(long timeout) throws InterruptedException {
checkSync();
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be non-negative");
}
if (timeout == 0) {
wait(0, 0);
} else {
wait(timeout, (int) (timeout % 1000000));
}
}
public final void wait(long timeout, int nanos) throws InterruptedException {
checkSync();
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be non-negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException("nanos must be between 0 and 999999");
}
if (timeout == 0 && nanos == 0) {
throw new IllegalArgumentException("timeout must be positive");
}
if (hasQueuedPredecessors()) {
throw new IllegalMonitorStateException();
}
setMonitorWait(true);
doWait(timeout, nanos);
}
public final void notify() {
checkSync();
notifyAll();
}
public final void notifyAll() {
checkSync();
for (Thread t : waitingThreads) {
t.interrupt();
}
waitingThreads.clear();
}
总结
在本文中,我们深入研究了 Java 多线程中 objectMonitor 的源码实现,了解了其如何提供监视器锁的支持,以及如何帮助开发者实现线程安全的 Java 程序。同时,我们还探讨了 synchronized 关键字的底层实现原理,以及 wait/notify 机制的源码解析。希望这些知识能够帮助您更好地理解和使用 Java 多线程。