Is it possible for a thread to Deadlock itself?

后端 未结 20 1349
暗喜
暗喜 2020-12-02 09:29

Is it technically possible for a thread in Java to deadlock itself?

I was asked this at an interview a while back and responded that it wasn\'t possible but the inte

20条回答
  •  Happy的楠姐
    2020-12-02 09:36

    Although the comments here are being pedantic about "deadlock" happening if at least two threads/actions are competing for the same resource...I think the spirit of this question was to discuss a need for Reentrant lock - especially in context of "recursive" locking

    Here's an example in python (I am certain the concept stays the same in Java): If you change the RLock to Lock (i.e. reentrant lock to lock, the thread will hang)

    import threading
    
    """
    Change RLock to Lock to make it "hang"
    """
    lock = threading.Condition(threading.RLock())
    
    
    def print_list(list):
        lock.acquire()
        if not list:
            lock.release()
            return
        print(list[0])
        print_list(list[1:])
        lock.release()
    
    
    print_list([1, 2, 3, 4, 5])
    

提交回复
热议问题