Question About Deadlock Situation in Java

前端 未结 6 2267
鱼传尺愫
鱼传尺愫 2020-12-08 12:06

I\'m learning about deadlocks in Java, and there\'s this sample code from Sun\'s official tutorial:

Alphonse and Gaston are friends, and great belie

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-08 12:30

    One important point to note is that it is not methods which are locked but object instances.

    When you call alphonse.bow(gaston), it tries to acquire the lock on alphonse. Once it has the lock, it prints a message, then calls gaston.bowBack(alphonse). At this point, it tries to acquire the lock on gaston. Once it has the lock, it prints a message, then releases the lock, and finally the lock on alphonse is released.

    In deadlock, the locks are acquired in such an order that there's no way for either thread to proceed.

    • Thread 1: acquires lock on alphonse
    • Thread 2: acquires lock on gaston
    • Thread 1: prints message
    • Thread 1: tries to acquire lock on gaston - can't, because Thread 2 already has it.
    • Thread 2: prints message
    • Thread 2: tries to acquire lock on alphonse - can't, because Thread 1 already has it.

提交回复
热议问题