pom.xml
<dependencies>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.1</version>
</dependency>
</dependencies>
RedissonManager.java
package org.example;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import java.util.concurrent.TimeUnit;
public class RedissonManager {
private static RedissonClient redisson;
public static void init() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://127.0.0.1:6379");
redisson = Redisson.create(config);
}
public static void shutdown() {
redisson.shutdown();
}
public static void testRedissonLock() {
RLock rLock = redisson.getLock("order");
System.out.println("我进入了方法!!" + Thread.currentThread().getName());
try {
rLock.lock(30, TimeUnit.SECONDS);
System.out.println("我获得了锁" + Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(5);
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println("我释放了锁" + Thread.currentThread().getName());
rLock.unlock();
}
}
}
Main.java
package org.example;
public class Main {
public static void main(String[] args) {
RedissonManager.init();
new Thread(() -> {
RedissonManager.testRedissonLock();
}).start();
new Thread(() -> {
RedissonManager.testRedissonLock();
}).start();
}
}
/*
我进入了方法!!Thread-2
我进入了方法!!Thread-3
我获得了锁Thread-3
我释放了锁Thread-3
我获得了锁Thread-2
我释放了锁Thread-2
*/
这样子,2个线程同时访问同一块临界资源,只有一个线程能拿到,同时由于依赖于redis,这个锁是跨jvm的。