think in java中Interrupting2.java示例中关于锁的问题?
本文介绍了think in java中Interrupting2.java示例中关于锁的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
书上说如果试图从第二个任务中调用f(),那么将总会音Mutex不可获得而被阻塞,我的疑问是这里构造器中获取lock的任务和调用lock的任务不是同一个任务吗?为什么Blocked2中调用blocked.f()的时候阻塞?下面是代码:
class BlockedMutex {
private Lock lock = new ReentrantLock();
public BlockedMutex() {
// Acquire it right away, to demonstrate interruption
// of a task blocked on a ReentrantLock:
lock.lock();
}
public void f() {
try {
// This will never be available to a second task
lock.lockInterruptibly(); // Special call
print("lock acquired in f()");
} catch(InterruptedException e) {
print("Interrupted from lock acquisition in f()");
}
}
}
class Blocked2 implements Runnable {
BlockedMutex blocked = new BlockedMutex();
public void run() {
print("Waiting for f() in BlockedMutex");
blocked.f();
print("Broken out of blocked call");
}
}
public class Interrupting2 {
public static void main(String[] args) throws Exception {
Thread t = new Thread(new Blocked2());
t.start();
TimeUnit.SECONDS.sleep(1);
System.out.println("Issuing t.interrupt()");
t.interrupt();
}
} /* Output:
Waiting for f() in BlockedMutex
Issuing t.interrupt()
Interrupted from lock acquisition in f()
Broken out of blocked call
*///:~
解决方案
BlockedMutex
的构造方法调用了Lock.lock()
以后没有Release()
调用
lock.lockInterruptibly()
和Lock.lock()
是在两个线程中
这篇关于think in java中Interrupting2.java示例中关于锁的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文