public String stock () {
Long threadId=Thread. CurrentThread (). The getId ();
Boolean lock=redisTemplate. OpsForValue (.) setIfAbsent (" lock ", threadId + ", "30, TimeUnit. SECONDS);
if (! The lock) {
System. The out. Println (" lock unreleased ");
return "";
}
//in order to avoid the code was not performed lock expired to lock renewal
New Thread () {
@ Override
Public void the run () {
While (true) {
Try {
Thread.sleep (15000);
} the catch (Exception e) {
E.f illInStackTrace ();
}
String locked=redisTemplate. OpsForValue (). The get (" lock ");
If (locked!=null & amp; & ! Locked. Equals (" ")) {
RedisTemplate. Expire (" lock ", 30, TimeUnit. SECONDS);
System. The out. Println ("===================renewal==============");
} else {
break;
}
}
}
}. The start ();
Try {
Int stock=Integer. The parseInt (redisTemplate opsForValue () get (" stock "));
If (stock & gt; 0 {
Stock -;
RedisTemplate. OpsForValue (). The set (the "stock", stock + "");
System. The out. Println (" successfully reduce inventory, the remaining "+ stock);
} else {
Insufficient System. Out. Println (" inventory ");
}
} the finally {
//delete the current thread lock
String lockValue=(https://bbs.csdn.net/topics/redisTemplate.opsForValue). The get (" lock ");
If (Long. The valueOf (lockValue)==threadId) {
RedisTemplate. Delete (" lock ");
}
}
Return "end";
}
CodePudding user response:
Renewal thread did not take the initiative to end, if got locked thread A release the lock, renew the thread after obtaining lock a1 thread B during sleep, will generate new renewal thread b1, a1 will not end, you do not know when a1 lock thread has changed, you don't have to judge whether take the thread id lock to open up the renewal thread id, then at the same time there may be many, many, many renew threads,CodePudding user response: