我没有看到以下代码如何产生看似违反对象锁定义的输出.当然只允许一个线程打印“获取锁定”消息,但他们都这样做?
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块.摘自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是一种更好的做法.