Display Lock for java Concurrent Programming learning

Keywords: Java less

Display lock and built-in lock

Advantages of built-in lock (Synchronized)

  1. Code concise
  2. The lock will not leak because the lock is not released.

Show Lock benefits

  1. Flexibility, lock acquisition can be interrupted, you can try to acquire locks.
  2. 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:

  1. lock(): get lock
  2. tryLock(): try to get the lock. true indicates that the lock is not applied.
  3. unlock(): release lock
  4. newCondition(): create a Condition

Condition interface

The main interface methods are as follows:

  1. await(): wait, similar to wait method
  2. signal(): wake up, similar to notify method
  3. 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.

Posted by PugJr on Fri, 18 Oct 2019 15:55:11 -0700