使用等待和通知的死锁

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

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

示例的插图将有所帮助。

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.

如果您没有多个锁,那么您没有死锁。 但是,您可以获得线程饥饿或其他可能类似于死锁的事情。

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

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

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

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

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

 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(); } }