Home >Java >javaTutorial >What are the methods of lock acquisition in Java?
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 { //如果不能获取锁,则直接做其他事情 }
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!