Java线程死锁

当两个线程相互等待对方释放同步监视器时就会发生死锁,Java虚拟机没有监测,也 没有采取措施来处理死锁情况,所以多线程编程时应该采取措施避免死锁出现。一旦 出现死锁,整个程序既不会发生任何异常,也不会给出任何提示,只是所有线程处于 阻塞状态,无法继续。 在系统中出现多个同步监视器的情况下很容易发生死锁。

为充分理解死锁,观察它的行为是很有用的。下面的例子生成了两个类,A和B,分别有foo( )和bar( )方法。这两种方法在调用其他类的方法前有一个短暂的停顿。主类,名为Deadlock,创建了A和B的实例,然后启动第二个线程去设置死锁环境。foo( )和bar( )方法使用sleep( )强迫死锁现象发生。

// An example of deadlock.
class A {
synchronized void foo(B b) {
    String name = Thread.currentThread().getName();
    System.out.println(name + " entered A.foo");
    try {
        Thread.sleep(1000);
    } catch(Exception e) {
        System.out.println("A Interrupted");
    }
    System.out.println(name + " trying to call B.last()");
    b.last();
}
synchronized void last() {
    System.out.println("Inside A.last");
}
}

class B {
synchronized void bar(A a) {
    String name = Thread.currentThread().getName();
    System.out.println(name + " entered B.bar");
    try {
        Thread.sleep(1000);
    } catch(Exception e) {
        System.out.println("B Interrupted");
    }
    System.out.println(name + " trying to call A.last()");
    a.last();
}
synchronized void last() {
    System.out.println("Inside A.last");
}
}
class Deadlock implements Runnable {
A a = new A();
B b = new B();
Deadlock() {
    Thread.currentThread().setName("MainThread");
    Thread t = new Thread(this, "RacingThread");
    t.start();
    a.foo(b); // get lock on a in this thread.
    System.out.println("Back in main thread");
}
public void run() {
    b.bar(a); // get lock on b in other thread.
    System.out.println("Back in other thread");
}
public static void main(String args[]) {
    new Deadlock();
}
}

运行程序后,输出如下:
MainThread entered A.foo
RacingThread entered B.bar
MainThread trying to call B.last()
RacingThread trying to call A.last()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值