gpt4 book ai didi

java - Java中的监视器和同步块(synchronized block)(看起来两个线程同时拥有一个监视器)

转载 作者:行者123 更新时间:2023-12-02 09:07:37 24 4
gpt4 key购买 nike

我试图理解我在本文末尾编写的程序中的 synchronized() block 。

有两个线程(ok)使用共享的lock 对象作为等待/通知的监视器。

o 在以下同步块(synchronized block)内等待 k 启动:

synchronized (lock) {
lock.wait(); // wait for K to be ready
}

k 然后通知 o 并等待它在该 block 内打印:

synchronized (lock) {
lock.notify(); // tell O to print
lock.wait(); // wait for O to print
}

我的问题是k如何进入带有lock的同步块(synchronized block)? o 不应该拥有lock(因为它调用了wait())吗? Java Tutorial says :

As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.

这是完整的程序:

public class OK implements Runnable {

private static final Object lock = new Object(); // monitor for wait/notify

private boolean isO;

public OK(boolean b) {
isO = b;
}

public static void main(String[] args) throws InterruptedException {

Thread o = new Thread(new OK(true));
Thread k = new Thread(new OK(false));
o.start();
k.start();
k.join(); // when k is done, we're done
System.out.println("Done.");

}

public void run() {

// run method is called for both o and k, so we separate the logic
try {
if (isO) {
doO();
} else {
doK();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

}

// O thread logic
private void doO() throws InterruptedException {

// K needs to be ready before I start
synchronized (lock) {
lock.wait(); // wait for K to be ready
}

System.out.print("O");
synchronized (lock) {
lock.notify(); // tell K I printed
}
}

// K thread logic
private void doK() throws InterruptedException {

// O is waiting for me to start

synchronized (lock) {
lock.notify(); // tell O to print
lock.wait(); // wait for O to print
}
System.out.println("K");
}

}

最佳答案

lock.wait 释放监视器。请参阅Object.wait() javadoc :

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

直觉可能会告诉您,“同步(锁)”意味着它在其包装的整个 block 期间保持该锁;但这不是它的工作原理。

关于java - Java中的监视器和同步块(synchronized block)(看起来两个线程同时拥有一个监视器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15595538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com