package com.yanxizhu;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: ReentrantLock
 * @author: <a href="mailto:batis@foxmail.com">清风</a>
 * @date: 2022/3/19 12:37
 * @version: 1.0
 */
public class LockDemo {

    public static void main(String[] args) {
        titck titck = new titck();
        new Thread(titck,"线程1").start();
        new Thread(titck,"线程2").start();
        new Thread(titck,"线程3").start();
    }

    public static class titck implements Runnable{
        Lock lock = new ReentrantLock();
        private int titck = 100;
        @Override
        public void run() {
            while(true){
                lock.lock();
                try{
                    if(titck>0){
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("剩余票数:"+--titck);
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
}

synchronized:隐式Lock

1、SynchronizationCode块

2、SynchronizationMethod

jdk1.5之后:Explicit Lock

3、SynchronizationLockLock

注意:是一个Explicit Lock,需要通过lock()Method上Lock,必须通过unlock()Method进行释放Lock。