Java如何使用线程解决死锁?
在Java编程中,如何使用线程解决死锁?
以下示例演示如何使用线程的概念解决死锁问题。
// from W w w .Y I I b AI.c o M
package com.yiibai;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class SolvingDeadlock extends ReentrantLock {
private static List deadlockLocksRegistry = new ArrayList();
private static synchronized void registerLock(SolvingDeadlock ddl) {
if (!deadlockLocksRegistry.contains(ddl))
deadlockLocksRegistry.add(ddl);
}
private static synchronized void unregisterLock(SolvingDeadlock ddl) {
if (deadlockLocksRegistry.contains(ddl))
deadlockLocksRegistry.remove(ddl);
}
private List hardwaitingThreads = new ArrayList();
private static synchronized void markAsHardwait(List l, Thread t) {
if (!l.contains(t))
l.add(t);
}
private static synchronized void freeIfHardwait(List l, Thread t) {
if (l.contains(t))
l.remove(t);
}
private static Iterator getAllLocksOwned(Thread t) {
SolvingDeadlock current;
ArrayList results = new ArrayList();
Iterator itr = deadlockLocksRegistry.iterator();
while (itr.hasNext()) {
current = (SolvingDeadlock) itr.next();
if (current.getOwner() == t)
results.add(current);
}
return results.iterator();
}
private static Iterator getAllThreadsHardwaiting(SolvingDeadlock l) {
return l.hardwaitingThreads.iterator();
}
private static synchronized boolean canThreadWaitOnLock(Thread t, SolvingDeadlock l) {
Iterator locksOwned = getAllLocksOwned(t);
while (locksOwned.hasNext()) {
SolvingDeadlock current = (SolvingDeadlock) locksOwned.next();
if (current == l)
return false;
Iterator waitingThreads = getAllThreadsHardwaiting(current);
while (waitingThreads.hasNext