Semaphore并發(fā)包
semaphore是基于計(jì)數(shù)的記號(hào)量,它可以設(shè)定一個(gè)資源的總數(shù)量,基于這個(gè)總數(shù)量,多線程競(jìng)爭(zhēng)獲取許可信號(hào),做自己的申請(qǐng)后,返回許可,并釋放資源.超過總數(shù)量后,線程申請(qǐng)?jiān)S可,信號(hào)將被阻塞,待有資源后,繼續(xù)執(zhí)行
下面是單線程實(shí)現(xiàn):
package cn.easyAccess.core.cache.local;
import java.util.concurrent.Semaphore;
/**
* @author lqyang
* @Title: ${file_name}
* @date 2018/9/511:29
*/
public class semaphoreDemo {
Semaphore semaphore = new Semaphore(1);
public void TestSemaphore(){
try {
//獲取資源許可數(shù)量
int var = semaphore.availablePermits();
if (var <= 0){
System.out.println(Thread.currentThread().getName()+"資源許可被占用");
}
//獲取許可
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"資源許可拿到-->start");
Thread.sleep(10);
System.out.println(Thread.currentThread().getName()+"資源處理完畢-->stop");
//將占用信號(hào)歸還
semaphore.release();
}catch (Exception e){
e.printStackTrace();
}
}
}
package cn.easyAccess.core.cache.local;
/**
* @author lqyang
* @Title: ${file_name}
* @date 2018/8/510:49
*/
public class semaphoreTest extends Thread{
semaphoreDemo semaphoreDemo;
public semaphoreTest(semaphoreDemo semaphoreDemo){
super();
this.semaphoreDemo = semaphoreDemo;
}
@Override
public void run() {
//TODO
semaphoreDemo.TestSemaphore();
}
}
package cn.easyAccess.core.cache.local;
/**
* @author lqyang
* @Title: ${file_name}
* @date 2018/9/511:54
*/
public class demoTest {
public static void main(String[] args) {
semaphoreDemo semaphoreDemo = new semaphoreDemo();
new semaphoreTest(semaphoreDemo).start();
}
}
執(zhí)行結(jié)果如下:

多線程實(shí)現(xiàn):
for (int i= 1; i< 5; i++){
new semaphoreTest(semaphoreDemo).start();
}
執(zhí)行結(jié)果如下:

下面是springboot具體實(shí)現(xiàn):
@GetMapping("/getOrderBuyerInfo")
public RespApi getOrderBuyerInfo(String keyword){
//可用資源數(shù)
int availablePermits = semaphore.availablePermits();
List<BuyersInfoModel> buyersInfoModels = new ArrayList<>();
if (availablePermits > 0){
logger.info("搶到資源");
}else {
logger.info("資源已被占用");
return RespApi.failure("No resources");
}
try{
//請(qǐng)求占用一個(gè)資源
semaphore.acquire(1);
String userId = getUser().getCreateUserId();
buyersInfoModels = orderService.getOrderShippingInfo(userId,keyword);
}catch (Exception e){
e.printStackTrace();
return RespApi.failure("error");
}finally {
//釋放資源
semaphore.release(1);
}
return RespApi.success(buyersInfoModels);
}
通過semaphore來實(shí)現(xiàn)線程安全。