import java.util.concurrent.locks.Lock;
/**
* @author lsy 分布式锁
* @version 1.0
* @date 2022/7/13 11:04
*/
public class Tests {
public static void main(String[] args){
Thread th1=new Thread(new MyThread(),"线程1");
Thread th2=new Thread(new MyThread(),"线程2");
th1.start();
th2.start();
}
static class MyThread implements Runnable{
Lock lock=new RedisLock();
@Override
public void run() {
new Orders().orders();
lock.lock();
new Stocks().getsocks();
lock.unlock();
}
}
}
/**
* @author lsy
* @version 1.0
* @date 2022/7/13 11:00
*/
public class Stocks {
private static int KETYNUMBER=1;
public boolean getsocks(){
if(KETYNUMBER>0){
KETYNUMBER--;
System.out.println("---------------------------------------");
System.out.println(Thread.currentThread().getName()+"减库成功");
return true;
}else{
System.out.println(Thread.currentThread().getName()+"减库失败");
return false;
}
}
}
/**
* @author lsy
* @version 1.0
* @date 2022/7/13 10:58
*/
public class Orders {
public void orders(){
//Thread 获取线程的名称
System.out.println(Thread.currentThread().getName()+"下单成功!");
}
}
import redis.clients.jedis.Jedis;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
public class RedisLock implements Lock {
ThreadLocal<Jedis> jedis = new ThreadLocal<Jedis>();
private static String LOCK_NAME = "LOCK";
private static String REQUEST_ID = "111111";
public void lock() {
if (jedis.get() ==null){
Jedis jedis = new Jedis("ip", 6379);
jedis.auth("密码");
this.jedis.set(jedis);
}
if (tryLock())
jedis.get().set(LOCK_NAME,REQUEST_ID,"NX","PX",5000);
}
public boolean tryLock() {
System.out.println("");
while(true){
Long ret = jedis.get().setnx(LOCK_NAME,REQUEST_ID);
if (ret==1)
return true;
}
}
public void unlock() {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object eval = jedis.get().eval(script, Collections.singletonList(LOCK_NAME), Collections.singletonList(REQUEST_ID));
}
public Condition newCondition() {
return null;
}
public void lockInterruptibly() throws InterruptedException {
}
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
}
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>