Java deadlock question

前端 未结 3 1607
-上瘾入骨i
-上瘾入骨i 2020-11-28 11:41

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

public class Deadlock {
    static class Friend {
        private final String name;
               


        
3条回答
  •  野性不改
    2020-11-28 12:19

    Here's how it probably will be executed.

    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.

提交回复
热议问题