在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()) {
Thread otherthread = (Thread) waitingThreads.next();
if (!canThreadWaitOnLock(otherthread, l)) {
return false;
}
}
}
return true;
} public SolvingDeadlock() {
this(false, false);
} public SolvingDeadlock(boolean fair) {
this(fair, false);
} private boolean debugging; public SolvingDeadlock(boolean fair, boolean debug) {
super(fair);
debugging = debug;
registerLock(this);
} public void lock() {
if (isHeldByCurrentThread()) {
if (debugging)
System.out.println("Already Own Lock");
super.lock();
freeIfHardwait(hardwaitingThreads, Thread.currentThread());
return;
}
markAsHardwait(hardwaitingThreads, Thread.currentThread());
if (canThreadWaitOnLock(Thread.currentThread(), this)) {
if (debugging)
System.out.println("Waiting For Lock");
super.lock();
freeIfHardwait(hardwaitingThreads, Thread.currentThread()); if (debugging)
System.out.println("Got New Lock");
} else {
throw new DeadlockDetectedException("DEADLOCK");
}
} public void lockInterruptibly() throws InterruptedException {
lock();
} public class DeadlockDetectingCondition implements Condition {
Condition embedded; protected DeadlockDetectingCondition(ReentrantLock lock, Condition embedded) {
this.embedded = embedded;
} public void await() throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads, Thread.currentThread());
embedded.await();
} finally {
freeIfHardwait(hardwaitingThreads, Thread.currentThread());
}
} public void awaitUninterruptibly() {
markAsHardwait(hardwaitingThreads, Thread.currentThread());
embedded.awaitUninterruptibly();
freeIfHardwait(hardwaitingThreads, Thread.currentThread());
} public long awaitNanos(long nanosTimeout) throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads, Thread.currentThread());
return embedded.awaitNanos(nanosTimeout);
} finally {
freeIfHardwait(hardwaitingThreads, Thread.currentThread());
}
} public boolean await(long time, TimeUnit unit) throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads, Thread.currentThread());
return embedded.await(time, unit);
} finally {
freeIfHardwait(hardwaitingThreads, Thread.currentThread());
}
} public boolean awaitUntil(Date deadline) throws InterruptedException {
try {
markAsHardwait(hardwaitingThreads, Thread.currentThread());
return embedded.awaitUntil(deadline);
} finally {
freeIfHardwait(hardwaitingThreads, Thread.currentThread());
}
} public void signal() {
embedded.signal();
} public void signalAll() {
embedded.signalAll();
}
} public Condition newCondition() {
return new DeadlockDetectingCondition(this, super.newCondition());
} private static Lock a = new SolvingDeadlock(false, true);
private static Lock b = new SolvingDeadlock(false, true);
private static Lock c = new SolvingDeadlock(false, true); private static Condition wa = a.newCondition();
private static Condition wb = b.newCondition();
private static Condition wc = c.newCondition(); private static void delaySeconds(int seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException ex) {
}
} private static void awaitSeconds(Condition c, int seconds) {
try {
c.await(seconds, TimeUnit.SECONDS);
} catch (InterruptedException ex) {
}
} private static void testOne() {
new Thread(new Runnable() {
public void run() {
System.out.println("thread one grab a");
a.lock();
delaySeconds(2);
System.out.println("thread one grab b");
b.lock();
delaySeconds(2);
a.unlock();
b.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("thread two grab b");
b.lock();
delaySeconds(2);
System.out.println("thread two grab a");
a.lock();
delaySeconds(2);
a.unlock();
b.unlock();
}
}).start();
} private static void testTwo() {
new Thread(new Runnable() {
public void run() {
System.out.println("thread one grab a");
a.lock();
delaySeconds(2);
System.out.println("thread one grab b");
b.lock();
delaySeconds(10);
a.unlock();
b.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("thread two grab b");
b.lock();
delaySeconds(2);
System.out.println("thread two grab c");
c.lock();
delaySeconds(10);
b.unlock();
c.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
System.out.println("thread three grab c");
c.lock();
delaySeconds(4);
System.out.println("thread three grab a");
a.lock();
delaySeconds(10);
c.unlock();
a.unlock();
}
}).start();
} private static void testThree() {
new Thread(new Runnable() {
public void run() {
System.out.println("thread one grab b");
b.lock();
System.out.println("thread one grab a");
a.lock();
delaySeconds(2);
System.out.println("thread one waits on b");
awaitSeconds(wb, 10);
a.unlock();
b.unlock();
}
}).start();
new Thread(new Runnable() {
public void run() {
delaySeconds(1);
System.out.println("thread two grab b");
b.lock();
System.out.println("thread two grab a");
a.lock();
delaySeconds(10);
b.unlock();
c.unlock();
}
}).start();
} public static void main(String args[]) {
int test = 1;
if (args.length > 0)
test = Integer.parseInt(args[0]);
switch (test) {
case 1:
testOne();
break;
case 2:
testTwo();
break;
case 3:
testThree();
break;
default:
System.err.println("usage: java DeadlockDetectingLock [ test# ]");
}
delaySeconds(60);
System.out.println("--- End Program ---");
System.exit(0);
}
} class DeadlockDetectedException extends RuntimeException {
public DeadlockDetectedException(String s) {
super(s);
}
}
Java

上述代码示例将产生以下结果 -

thread one grab a
Waiting For Lock
thread two grab b
Got New Lock
Waiting For Lock
Got New Lock
thread one grab b
Exception in thread "Thread-1" thread two grab a
Waiting For Lock
com.yiibai.DeadlockDetectedException: DEADLOCK
at com.yiibai.SolvingDeadlock.lock(SolvingDeadlock.java:102)
at com.yiibai.SolvingDeadlock$2.run(SolvingDeadlock.java:213)
at java.lang.Thread.run(Unknown Source)

随机推荐

  1. linux 多线程基础

    参考出处:http://www.cnblogs.com/skynet/archive/2010/10/30/1865267.html 1.进程与线程 进程是程序代码在系统中的具体实现.进程是拥有所需资 ...

  2. bootstrap基本模板

    <!DOCTYPE html><!--html5文档格式--> <html lang="zh-CN"><!--申明语言是中文简体--> ...

  3. Android runProguard配置 导致module lib 中的包编译时无法识别

    今天写代码时用到了另一个lib型的工程,把它添加到dependencies后,在原工程中可以引用lib中的文件了,但是编译时就会报错,提示包不存在,后来在build.gradle中设置runProgu ...

  4. Catalog与Schema

    按照SQL标准的解释,在SQL环境下Catalog和Schema都属于抽象概念,可以把它们理解为一个容器或者数据库对象命名空间中的一个层次,主要用来解决命名冲突问题.从概念上说,一个数据库系统包含多个 ...

  5. linux_nand_driver

    本文的主要目的是,看了之后,你应该对Nand Flash的硬件特性以及对应的Linux下软件平台有了基本的认识,进一步地,对如何实现Linux下的Nand Flash的驱动,知道要做哪些事情了,以及大 ...

  6. [Linux]学习笔记(1)

    说到Linux就不得不提UNIX,因为Linux是从UNIX系统发展来的,两系统极为相似,可以在UNIX操作系统上使用的功能都可以在Linux上使用,只可能有少许的差异: UNIX系统中所有的东西都是 ...

  7. Windows的命令行怎么支持通配符

    摸索出一个小技巧,虽然Windows的命令行本身不支持通配符,但可以在脚本里把传进来的参数当通配符用 只要加上@ARGV = glob "@ARGV";就行了 @ARGV = gl ...

  8. ORA-942 SP2-0611

    环境:oracle 11.2.04 问题描述: 在使用hr用户启用set autot trace时报错 set">HR@test>set autot trace; Error O ...

  9. hadoop安全模式

      hadoop安全模式在分布式文件系统启动的时候,开始的时候会有安全模式,当分布式文件系统处于安全模式的情况下,文件系统中的内容不允许修改也不允许删除,直到安全模式结束.安全模式主要是为了系统启动的 ...

  10. PHP选择排序

    选择排序,非常的直观,也相对简单. 思路如下: 假设,从小到大排序. 首先,第一轮循环,从所有数组中,找出最小的元素,然后将其下标记录下来. 然后,确定不是第一个元素,则和第一个元素进行交换. 接下来 ...