How this java code produces deadlock?

前端 未结 5 1735
被撕碎了的回忆
被撕碎了的回忆 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:14

    The dealock will happen if both enters the bow() method at the same time, or during

    System.out.println();
    

    If you don't see both of the "has bowed back to me!" messages, then the deadlock occured!

    If the first thread terminated before the second started there will be no deadlock.

    Extend the code with Thread.sleep(1000);

    public synchronized void bow(Friend bower) {
    System.out.println(....);
    Thread.sleep(1000);
    ...
    }
    

    then both threads enter bow() and dealock will occur.

提交回复
热议问题