package com.liquidnet.service.reconciliation.service.test;

/**
 * @author AnJiabin <jiabin.an@lightnet.io>
 * @version V1.0
 * @Description:
 * @class: TryLockTest
 * @Package com.liquidnet.service.reconciliation.service.test
 * @Copyright: LightNet @ Copyright (c) 2020
 * @date 2020/12/17 1:55 下午
 */

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
    //学习 tryLock
//tryLock()方法是有返回值的，它表示用来尝试获取锁，如果获取成功，则返回true，如果获取失败（即锁已被其他线程获取），则返回false，这个方法无论如何都会立即返回。在拿不到锁时不会一直在那等待。
public class TryLockTest {

        public static void main(String[] args) {

            System.out.println("开始");
            final Lock lock = new ReentrantLock();
            new Thread() {
                @Override
                public void run() {
                    String tName = Thread.currentThread().getName();
                    if (lock.tryLock()) {
                        System.out.println(tName + "获取到锁！");
                    } else {
                        System.out.println(tName + "获取不到锁！");
                        return;
                    }
                    try {
                        for (int i = 0; i < 5; i++) {
                            System.out.println(tName + ":" + i);
                        }
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        System.out.println(tName + "出错了！！！");
                    } finally {
                        System.out.println(tName + "释放锁！！");
                        lock.unlock();
                    }

                }
            }.start();

            new Thread() {
                @Override
                public void run() {
                    String tName = Thread.currentThread().getName();

                    if (lock.tryLock()) {
                        System.out.println(tName + "获取到锁！");
                    } else {
                        System.out.println(tName + "获取不到锁！");
                        return;
                    }

                    try {
                        for (int i = 0; i < 5; i++) {
                            System.out.println(tName + ":" + i);
                        }

                    } catch (Exception e) {
                        System.out.println(tName + "出错了！！！");
                    } finally {
                        System.out.println(tName + "释放锁！！");
                        lock.unlock();
                    }
                }
            }.start();

            System.out.println("结束");
        }
}
