Display lock and built-in lock
Advantages of built-in lock (Synchronized)
- Code concise
- The lock will not leak because the lock is not released.
Show Lock benefits
- Flexibility, lock acquisition can be interrupted, you can try to acquire locks.
- Read more and write less.
usage
If you can use the built-in lock, you can use the built-in lock. If you can't use the built-in lock, you can use the display lock.
Lock interface
The main interface methods are as follows:
- lock(): get lock
- tryLock(): try to get the lock. true indicates that the lock is not applied.
- unlock(): release lock
- newCondition(): create a Condition
Condition interface
The main interface methods are as follows:
- await(): wait, similar to wait method
- signal(): wake up, similar to notify method
- signalAll(): wake up all, similar to the notifAll method
Usage form
Lock lock = new ReentrantLock(); .... lock.lock();//Get lock try{ //Business logic }finally{ lock.unlock();//Pay attention to the release here, or the lock will leak. }
Example
public class LockDemo { Lock lock = new ReentrantLock(); static int num = 0; public void addNum(int value) { lock.lock(); try { int temp = num; num = num + value; Thread.sleep(100); System.out.println(value + "+" + temp + "=" + num); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } static class AddThread1 extends Thread { LockDemo lockDemo; public AddThread1(LockDemo lockDemo) { this.lockDemo = lockDemo; } @Override public void run() { lockDemo.addNum(1); } } static class AddThread2 extends Thread { LockDemo lockDemo; public AddThread2(LockDemo lockDemo) { this.lockDemo = lockDemo; } @Override public void run() { lockDemo.addNum(2); } } public static void main(String[] args) { LockDemo lockDemo = new LockDemo(); AddThread1 addThread1 = new AddThread1(lockDemo); AddThread2 addThread2 = new AddThread2(lockDemo); addThread1.start(); addThread2.start(); } }
The operation results are as follows:
The results show that synchronized The result is the same. The lock is unlocked successfully.