首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

死锁范例

2012-11-17 
死锁实例下面这道题,是考死锁的,比较简单,想两个问题:1.什么时候会造成死锁2.wait和notify释放了哪个锁,因

死锁实例

下面这道题,是考死锁的,比较简单,想两个问题:

1.什么时候会造成死锁

2.wait和notify释放了哪个锁,因为题目中有两个锁。

?

import java.util.LinkedList;


public class DeadLockTest {
?? ?LinkedList list = new LinkedList(); ?
?? ? ?
??? public synchronized void push(Object x) { ?
?? ??? ?System.out.println("push");
??????? synchronized (list) { ?
??????????? list.addLast(x); ?
??????????? notify(); ?
??????? } ?
??? } ?
?
??? public synchronized Object pop() throws Exception {?? ?
??????? synchronized (list) { ?
??????????? if (list.size() <= 0) { ?
?????????? ??? ?wait(); ?
??????????? } ?
??????????? return list.removeLast(); ?
??????? } ?
??? } ?
?? ?
??? public static void main(String[] args) throws InterruptedException {
?? ??? ?final DeadLockTest deadLockTest = new DeadLockTest();
?? ??? ?Thread thread = new Thread(new Runnable() {
?? ??? ??? ?public void run() {
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?deadLockTest.pop();
?? ??? ??? ??? ?} catch (Exception e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?});
?? ??? ?thread.start();
?? ??? ?Thread.sleep(2000);
?? ??? ?Thread threadPush = new Thread(new Runnable() {
?? ??? ??? ?public void run() {
?? ??? ??? ??? ?try {
?? ??? ??? ??? ??? ?deadLockTest.push("push thread");
?? ??? ??? ??? ?} catch (Exception e) {
?? ??? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?});
?? ??? ?threadPush.start();
?? ??? ?
?? ?}
}

?

显然当stack中没有元素时,pop的时候会释放this对象锁,当其它线程进行push或者pop时,list并没有释放,一直等待list的释放,但是wait又在等待其它线程唤醒,因此出现了死锁。

?

热点排行