How this java code produces deadlock?

前端 未结 5 1717
被撕碎了的回忆
被撕碎了的回忆 2020-12-21 10:23

i am going through oracle docs for deadlock.. i found this code

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


        
5条回答
  •  天命终不由人
    2020-12-21 11:07

    You have 2 objects, alphonse and gaston and 2 threads, Thread1 and Thread2

    Suppose this happens:

    1. Thread1: alphonse enters the bow() method. and will hold a lock on the alphonse object

    2. Thread2: gaston enters the bow() method. and will hold a lock on the gaston object

    3. Thread1: alphonse while in the bow() method, calls bowBack() on the gaston object.

      -> Thread1 will block, since Thread2 already has the lock on gaston

    4. Thread2: gaston while in the bow() method, calls bowBack() on the alphonse object.

      -> Thread2 will block, since Thread1 already has the lock on alphonse

    So now Thread1 is waiting for Thread2. And Thread2 is waiting for Thread1. This is a deadlock.

提交回复
热议问题