死锁
下文讲述死锁的相关知识简介说明,如下所示:
两个线程中的parent表示的是同一个对象,child亦然,此时就会发生死锁
我们将两个或多个线程阻塞等待其它线程处于死锁状态的线程所持有的锁,这种现象我们称之为“死锁” 死锁通常放生在多个线程按照不同的顺序访问同一组锁资源时发生例:
线程1锁住了A,然后尝试对B进行加锁 同时线程2已经锁住了B 接着尝试对A进行加锁 以上的情况就产生了死锁 ----------------------------------- 线程1永远得不到B,线程2也永远得不到A 它们将永远阻塞下去 这种现象就是一个死锁例:
public class TreeNode {
TreeNode parent = null;
list children = new ArrayList();
public synchronized void addChild(TreeNode child){
if(!this.children.contains(child)) {
this.children.add(child);
child.setParentOnly(this);
}
}
public synchronized void addChildOnly(TreeNode child){
if(!this.children.contains(child){
this.children.add(child);
}
}
public synchronized void setParent(TreeNode parent){
this.parent = parent;
parent.addChildOnly(this);
}
public synchronized void setParentOnly(TreeNode parent){
this.parent = parent;
}
}
当线程1调用parent.addChild(child)方法的同时有另外一个线程2调用child.setParent(parent)方法两个线程中的parent表示的是同一个对象,child亦然,此时就会发生死锁
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


