Home > Java > javaTutorial > What are the methods of lock acquisition in Java?

What are the methods of lock acquisition in Java?

王林
Release: 2023-05-19 13:13:06
forward
2040 people have browsed it

1. Acquisition methods

lock(), tryLock(), tryLock(long time, TimeUnit unit) and lockInterruptibly() are all used to acquire locks.

(1) The lock() method is the most commonly used method, which is used to obtain the lock. If the lock has been acquired by another thread, wait.

(2) The tryLock() method has a return value, which means it is used to try to acquire the lock. If the acquisition is successful, it returns true. If the acquisition fails (that is, the lock has been acquired by another Thread acquisition), it returns false, which means that this method will return immediately no matter what. You won't be waiting there when you can't get the lock.

(3) The tryLock(long time, TimeUnit unit) method is similar to the tryLock() method, but the only difference is that this method will wait for a certain period of time when it cannot get the lock , if the lock cannot be obtained within the time limit, false will be returned. Returns true if the lock was obtained initially or during the waiting period.

(4) The lockInterruptibly() method is special. When acquiring a lock through this method, if the thread is waiting to acquire the lock, the thread can respond to the interrupt, that is, interrupts the waiting state of the thread. In other words, when two threads want to acquire a lock through lock.lockInterruptibly() at the same time, if thread A acquires the lock at this time, and thread B is only waiting, then threadB.interrupt is called on thread B. The () method can interrupt the waiting process of thread B.

2. Example

Take trylock as an example.

Lock lock = ...;
if(lock.tryLock()) {
     try{
         //处理任务
     }catch(Exception ex){
         
     }finally{
         lock.unlock();   //释放锁
     }
}else {
    //如果不能获取锁,则直接做其他事情
}
Copy after login

The above is the detailed content of What are the methods of lock acquisition in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template