Semaphore juc(java.util.concurrent)包中的信号量控制类:作用是有限的资源分配合理,比如6个车抢3个停车位,同一时间只能有3个车可以抢到停车位,其他车只能等着。主要方法:acquire(),release()
多个线程争抢少量资源,对这些资源同时加锁,保证资源合理分配,不会出现同一资源同一时间被多个线程抢到
代码举例:
package com.example.mybatisplus;
import org.junit.Test;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Semaphore juc(java.util.concurrent)包中的信号量控制类:
* 作用是有限的资源分配合理:
* 比如6个车抢3个停车位,同一时间只能有3个车可以抢到停车位,
* 其他车只能等着。主要方法:acquire(),release() 多个线程争抢少量资源,
* 对这些资源同时加锁,保证资源合理分配,不会出现同一资源同一时间被多个线程抢到
* 秒杀场景可以使用Semphore
*/
public class SemaphoreTest {
/**
* 6辆车抢3个车位
*/
@Test
public void SemaphoreTest() {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"号车抢到了车位");
TimeUnit.SECONDS.sleep(new Random(10).nextInt());
System.out.println(Thread.currentThread().getName()+"停了一会儿开走了!");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
},i+"号车").start();
}
}
}
RedissonClient的semaphore是分布式的信号量控制类,可以对分布式应用访问进行统一控制
代码示例:
@GetMapping("/redisSemaphoreTest")
public void redisSemaphoreTest(){
RSemaphore rSemaphore = redissonClient.getSemaphore("semaphore");
rSemaphore.trySetPermits(3);
try {
rSemaphore.acquire();
//System.out.println("8002获取了资源,开始处理业务逻辑"+Thread.currentThread().getName());
redisTemplate.opsForList().rightPush("log","8001获取了资源,开始处理业务逻辑"+Thread.currentThread().getName());
TimeUnit.SECONDS.sleep(new Random(10).nextInt());
//System.out.println("8002处理完业务逻辑,释放资源。。。。。。。。"+Thread.currentThread().getName());
redisTemplate.opsForList().rightPush("log","8001处理完业务逻辑,释放资源。。。。。。。。"+Thread.currentThread().getName());
rSemaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}