本文介绍了Java死锁问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以解释为什么这段代码中存在死锁。谢谢

can anyone explain me why there is a deadlock in this code.Thanks

public class Deadlock {
    static class Friend {
        private final String name;
        public Friend(String name) {
            this.name = name;
        }
        public String getName() {
            return this.name;
        }
        public synchronized void bow(Friend bower) {
            System.out.format("%s: %s has bowed to me!%n",
                    this.name, bower.getName());
            bower.bowBack(this);
        }
        public synchronized void bowBack(Friend bower) {
            System.out.format("%s: %s has bowed back to me!%n",
                    this.name, bower.getName());
        }
    }

    public static void main(String[] args) {
        final Friend alphonse = new Friend("Alphonse");
        final Friend gaston = new Friend("Gaston");
        new Thread(new Runnable() {
            public void run() { alphonse.bow(gaston); }
        }).start();
        new Thread(new Runnable() {
            public void run() { gaston.bow(alphonse); }
        }).start();
    }
}


推荐答案

这里是它可能会被执行。

Here's how it probably will be executed.


  1. 输入 alphonse.bow(gaston); ,alphonse现已锁定,因为已同步关键字

  2. 输入 gaston.bow(alphonse); ,gaston现已锁定

  3. 无法从第一个<$ c $执行 bower.bowBack(this); c> bow 方法调用因为gaston(bower)被锁定。等待锁被释放。

  4. 无法从第二个执行 bower.bowBack(this); bow 方法调用因为alphonse(bower)被锁定。等待锁被释放。

  1. Enter alphonse.bow(gaston);, alphonse is now locked due to synchronized keyword
  2. Enter gaston.bow(alphonse);, gaston is now locked
  3. Can't execute bower.bowBack(this); from first bow method call because gaston (bower) is locked. Wait for lock to be released.
  4. Can't execute bower.bowBack(this); from second bow method call because alphonse (bower) is locked. Wait for lock to be released.

两个线程互相等待释放锁定。

Both threads wait for each other to release lock.

这篇关于Java死锁问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 18:06