gpt4 book ai didi

java - 使用内在锁进入 block

转载 作者:搜寻专家 更新时间:2023-11-01 01:54:21 24 4
gpt4 key购买 nike

我看不出以下代码如何产生似乎违反对象锁定义的输出。当然应该只允许一个线程打印“获得的锁”消息,但他们都这样做了?

class InterruptThreadGroup {
public static void main(String[] args) {
Object lock = new Object();
MyThread mt1 = new MyThread(lock);
MyThread mt2 = new MyThread(lock);
mt1.setName("A");
mt1.start();
mt2.setName("B");
mt2.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
// Thread.currentThread().getThreadGroup().interrupt();
}
}

class MyThread extends Thread {
private Object lock;

public MyThread(Object l) {
this.lock = l;

}

public void run() {
synchronized (lock) {
System.out.println(getName() + " acquired lock");
try {
lock.wait();
} catch (InterruptedException e) {
System.out.println(getName() + " interrupted.");
}
System.out.println(getName() + " terminating.");
}
}
}

最佳答案

是因为调用lock.wait()释放了锁,让第二个线程进入synchronized block 。摘自 javadoc

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.

请注意,您的代码中存在一些问题,例如:

  • 你不应该在 while 循环之外等待
  • 任何地方都没有通知,所以你可以永远等待
  • 让您的任务实现 Runnable 并将其作为参数传递给 Thread 的构造函数比直接扩展 Thread 更好。

关于java - 使用内在锁进入 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14485178/

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