ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > >
homework7 Version 0
👤 Author: by 653968106qqcom 2020-11-11 03:54:39
My example:



The running result of deadlock:



Four necessary conditions of deadlock:

  1. Mutual exclusion: there is a resource that can only be allocated to one thread (also known as thread) at a certain time;

  2. Hold and wait: when the requested resource is occupied, resulting in thread blocking, the resource occupier not only does not need to release the resource, but also can continue to request more resources;

  3. No preemption: the mutually exclusive resources acquired by the thread can not be forcibly deprived. In other words, only the resource occupier can release the resource;

  4. Circular wait: several threads acquire mutually exclusive resources in different order, thus forming a circular wait situation. Imagine in a ring chain composed of multiple threads, each thread is waiting for the next thread to release the resources it holds.


In this example, object1 and object2 are set as static to ensure that there is only one instance. And as a result it generates a deadlock.

 

Solution:

move the "synchronized (o2){System.out.println("flag=0 gets Object2's lock");}" out of "synchronized (o1)" and "synchronized (o1){System.out.println("flag=1 gets Object1's lock");}" out of  "synchronized (o2)".

Modified Code:



Running result:



 

Please login to reply. Login

Reversion History

Loading...
No reversions found.