Jelajahi Sumber

redisson 测试超时

yegang 2 tahun lalu
induk
melakukan
018700f824
1 mengubah file dengan 57 tambahan dan 0 penghapusan
  1. 57 0
      src/test/java/com/sw/RedissonTest.java

+ 57 - 0
src/test/java/com/sw/RedissonTest.java

@@ -125,7 +125,64 @@ public class RedissonTest {
         }
         log.info("子线程都已执行完毕,main函数可以结束了!");
     }
+    @Test
+    public void trylock2() {
+        RLock lock = redissonClient.getLock("mask-" + 1);
+        new Thread(() -> {
+            String threadName = Thread.currentThread().getName();
+            log.info("线程:{} 正在尝试获取锁。。。", threadName);
+            boolean b = false;
+            try {
+                b = lock.tryLock(4000, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+            if (b) {
+                try {
+
+                    Thread.sleep(6000);
+                    log.info("{}:业务执行完成", threadName);
+                    count.countDown();
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                } finally {
+                    lock.unlock();
+                    log.info("线程:{},释放了锁", threadName);
+                }
+            } else {
+                log.info("{}:没有获取到锁,锁已被占用", threadName);
+            }
+        }).start();
+        new Thread(() -> {
+            String threadName = Thread.currentThread().getName();
+            log.info("线程:{} 正在尝试获取锁。。。", threadName);
+            try {
+                if (lock.tryLock(4000, TimeUnit.MILLISECONDS)) {
+                    try {
 
+                        Thread.sleep(6000);
+                        log.info("{}:业务执行完成", threadName);
+                        count.countDown();
+                    } catch (InterruptedException e) {
+                        e.printStackTrace();
+                    } finally {
+                        lock.unlock();
+                        log.info("线程:{},释放了锁", threadName);
+                    }
+                } else {
+                    log.info("{}:没有获取到锁,锁已被占用", threadName);
+                }
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }).start();
+        try {
+            count.await();
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+        log.info("子线程都已执行完毕,main函数可以结束了!");
+    }
     @Test
     public void timeout() {