package com.izouma.nineth;

import org.junit.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;

public class TestRedissonLock extends ApplicationTests {

    @Autowired
    private RedissonClient redissonClient;

    @Test
    public void testLock() throws InterruptedException {
        RLock lock = redissonClient.getLock("testLock");
        Thread t1 = new Thread(() -> {
            lock.lock(10, TimeUnit.SECONDS);
            System.out.println("线程1获取锁");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
            System.out.println("线程1释放锁");
        });
        Thread t2 = new Thread(() -> {
            lock.lock(10, TimeUnit.SECONDS);
            System.out.println("线程2获取锁");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
            System.out.println("线程2释放锁");
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
