package com.izouma.nineth; import org.junit.jupiter.api.Test; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import java.util.concurrent.TimeUnit; import org.springframework.boot.test.context.SpringBootTest; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TestRedissonLock { @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(); } }