The operating environment of this tutorial: Windows 7 system, Java 10 version, DELL G3 computer.
1. Obtaining method
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 locks . 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), it returns false, which means this The method returns 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 difference is that this method will wait for a certain period of time when the lock cannot be obtained. If the lock cannot be obtained within the time limit, , it returns false. 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, interrupt the waiting state of the thread. That is to say, 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 the threadB.interrupt() method is called on thread B. Can interrupt the waiting process of thread B.
2.Examples
Take trylock as an example.
Lock lock = ...; if(lock.tryLock()) { try{ //Processing tasks }catch(Exception ex){ }finally{ lock.unlock(); //Release the lock } }else { //If the lock cannot be acquired, do other things directly}
There are many methods stored in the java interface to facilitate direct calls when using threads. Everyone is familiar with the lock interface, and we have already had a preliminary understanding of the concept. So the method of acquiring the lock must not be very clear yet.
The above are the four methods of lock acquisition in Java. After reading the article, you can strengthen your memory and understanding in this area. If you are interested in other methods of acquiring locks, you can also find relevant codes for practice after class.