Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What's the difference between synchronize and lock?

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what is the difference between synchronize and lock. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Both are based on the mechanism of pessimistic locking.

If the current thread 1 acquires the lock, thread 2 waits.

If thread 1 is blocked, thread 2 will wait forever, while the Lock lock will not necessarily wait. If the attempt does not get the lock, the thread can end without waiting all the time.

(a thread releases the lock after executing the synchronization code; b thread releases the lock when an exception occurs during thread execution)

Lock needs to release the lock manually in finally (unlock () method releases the lock), otherwise it is easy to cause thread deadlock.

1. First of all, synchronized is the built-in keyword for java. At the jvm level, Lock is a java class.

2.synchronized cannot determine whether to acquire the status of the lock, and Lock can determine whether to acquire the lock.

3.synchronized automatically releases the lock.

4. Two threads 1 and 2 with the synchronized keyword

5.synchronized locks are reentrant, uninterruptible, and unfair, while Lock locks are reentrant, judgeable, and fair (both)

6.Lock locks are suitable for synchronization problems with a large number of synchronized code, and synchronized locks are suitable for synchronization problems with a small amount of code.

This is the end of the article on "what's the difference between synchronize and lock". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report