使用等待和通知的死锁

时间:2013-11-11 14:15:43

标签: java deadlock

我试图了解如何创建死锁。我已经明白,通过在两个同步方法上使用两个线程,可以创建死锁。 通过网络中的许多例子。

可以使用wait和notify创建死锁吗? 每次线程等待时,都会收到通知。那么这最终会如何陷入僵局?

示例的插图将有所帮助。

4 个答案:

答案 0 :(得分:4)

Deadlock is caused when two threads try to obtain the same, multiple locks in different order:

    // T1
    synchronized (A) {
      synchronized (B) {
        // ...
      }
    }

    // T2
    synchronized (B) {
      synchronized (A) {
        // ...
      }

}

防止死锁的唯一方法是确保所有线程以相同的顺序获取锁定 - 要么它们都执行A然后执行B,要么它们都执行B然后执行A.

如果您没有多个锁,那么您就不会陷入僵局。但是,您可能会遇到线程饥饿或其他可能类似于死锁的事情。

答案 1 :(得分:1)

除非某些代码明确通知,否则不会通知正在等待的线程。因此,您正在寻找的示例绝对是微不足道的:

public static void main(String[] args) {
   synchronized(String.class) {
       String.class.wait();
   }
}

这永远挂起。但从技术上讲,它不是一个死锁,它需要在一个闭合循环中涉及两个或多个线程,每个线程等待下一个线程取消阻塞它。

答案 2 :(得分:0)

假设线程1在方法A上进入同步块,然后等待。然后,线程2尝试在方法A上进入同步块。线程1正在等待通知,并且线程2正在等待同步块。一切都在等待。其他一些线程必须通知线程1正在等待的对象。这只是一种可能造成死锁的情况。有各种方法可以做到这一点。

答案 3 :(得分:0)

接近等待/通知死锁的东西:

public class Example
{
    volatile boolean isNotified = false;

    public synchronized void method1() {
        try
        {
            isNotified = false;
            while (!isNotified)
                wait();
            notifyAll();
            System.out.println("Method 1");
        } catch (InterruptedException e) {/*NOP*/}
    }

    public synchronized void method2() {
        try {
            isNotified = true;
            while (isNotified)
                wait();
            notifyAll();

            System.out.println("Method 2");
        } catch (InterruptedException e) {/*NOP*/}

    }

    public static void main(String[] args)
    {
        Example example = new Example();

        Thread thread1 = new Thread()
        {

            public void run()
            {
                example.method1();
            }
        };

        Thread thread2 = new Thread()
        {

            public void run()
            {
                example.method2();
            }
        };

        thread1.start();
        thread2.start();
    }
}