Multi-threaded concurrent programming notes 04 (XiaoDi Classroom) ---Lock

Classification of locks:

 

 Use of lock:

So what is the difference between lock and synchronized?
 

 

Implement your own lock:

Through the running results, we found that there seemed to be a deadlock feeling, and there was no successful reentry. This is wrong, so we have to change our custom lock:

 

 

 

After this change, we can complete the reentry function. 

 

 

 

 

We can see that this value is incorrect.

Because the thread sleeps, the value of j will be read without +1.

According to what we have learned before, we should be able to use the synchronized keyword modification method to achieve thread safety through locking. But this approach is too wasteful of resources. We want that when writing, other threads cannot write or read, but when reading, all threads can read, but cannot write.

In this case we can use read-write locks:

 

We now add read locks and write locks, and then run:

 The values ​​are all 3, proving that i and j are the same.

You can try reading, reading, writing, writing and writing operations on the console, and perform thread debugging. You can find that reading and reading are shared, and other operations are mutually exclusive.

Lock downgrade:

There is such a simple piece of code, we first call the write lock, and then call the read lock:

 

Note: After downgrading, the write lock will not be directly downgraded to a read lock, and will not be released with the release of the read lock, so the write lock needs to be explicitly released.

Is there a lock upgrade?

No results were obtained.

Indicates that there is no lock upgrade in this class.

 

 

 

The values ​​​​are all 4, which is definitely not in line with our expectations.

At this time we can use our read-write lock.

 

 We find that the current output is realistic.

 

 

 

Guess you like

Origin blog.csdn.net/weixin_52618349/article/details/129782952