在Java多线程中避免死锁的策略之一是使用超时。假设一个线程在一个资源上获得了锁,现在正在等待另一个资源上的锁。在一定时间后,如果它不能获得resource2上的锁,那么它应该停止等待resource2上的锁。此外,它还应该释放对resource1的锁定。这样就避免了死锁。
但是如何在Java中实现它呢?如何显式“释放”锁?如何定义等待锁定的超时。
什么是确切的java命令和语法。有什么关于hello-worldish的例子吗?
发布于 2012-12-06 18:35:15
这是一个人为设计的例子,其中包含2个锁和2个线程,它们试图以不同的顺序获取它们。如果没有超时,代码将死锁。
public static void main(String[] args) throws Exception {
final ReentrantLock lock1 = new ReentrantLock();
final ReentrantLock lock2 = new ReentrantLock();
Runnable try1_2 = getRunnable(lock1, "lock 1", lock2, "lock 2");
Runnable try2_1 = getRunnable(lock2, "lock 2", lock1, "lock 1");
new Thread(try1_2).start();
new Thread(try2_1).start();
}
private static Runnable getRunnable(final ReentrantLock lock1, final String lock1Name, final ReentrantLock lock2, final String lock2Name) {
return new Runnable() {
@Override
public void run() {
try {
if (lock1.tryLock(1, TimeUnit.SECONDS)) {
System.out.println(lock1Name + " acquired in thread " + Thread.currentThread());
if (lock2.tryLock(1, TimeUnit.SECONDS)) {
System.out.println(lock2Name + " acquired in thread " + Thread.currentThread());
Thread.sleep(2000);
} else {
System.out.println("Could not acquire "+lock2Name + " in thread " + Thread.currentThread());
lock1.unlock();
System.out.println(lock1Name + " released in thread " + Thread.currentThread());
}
} else {
System.out.println("Could not acquire " + lock1Name + " in thread " + Thread.currentThread());
}
} catch (InterruptedException e) {
//you should not ignore it
} finally {
if (lock1.isHeldByCurrentThread()) lock1.unlock();
if (lock2.isHeldByCurrentThread()) lock2.unlock();
}
}
};
}发布于 2012-12-06 18:25:11
Lock in Java
Use tryLock(timeout, timeunits);如果
在给定的等待时间内是空闲的,并且当前线程没有被中断,则获取锁。如果锁可用,则此方法立即返回,返回值为
true。
如果锁不可用,则出于线程调度的目的,当前线程将变为禁用的,并处于休眠状态,直到发生以下三种情况之一:
锁是当前线程获取的;
或者其他线程中断当前线程,支持获取锁的中断;
或者指定的等待时间已过
发布于 2012-12-06 18:30:47
希望这能有所帮助,
Lock lock = null;
lock=....;
if (lock.tryLock(15L, TimeUnit.SECONDS)) {
try {
........
} finally {
lock.unlock();
}
} else {
// do sumthing
}https://stackoverflow.com/questions/13741479
复制相似问题