如果你有一個東西, 你想别人觸碰它的時候,不能同時觸碰,需要按照你想要的每次多少人來觸碰。
算了,不做比喻了,代碼原理其實也簡單,我們直接先看代碼,我再做簡單的解釋(估計不用看解釋也能懂):
package com.semaphore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.concurrent.Semaphore;
/**
* @Author : JCccc
* @CreateTime : 2018-11-27
* @Description :
* @Point: Keep a good mood
**/
@Controller
public class SemaphoreController {
//定義信号資源包的總數 隻有2個
Semaphore semaphore=new Semaphore(2);
@GetMapping("/request")
@ResponseBody
public String Resquest(){
//設定這個接口可用的資源數
int availablePermits=semaphore.availablePermits();
if(availablePermits>0){
System.out.println("搶到資源");
}else{
System.out.println("資源已被占用,稍後再試");
return "Resource is busy!";
}
try {
//請求占用一個資源
semaphore.acquire(1);
System.out.println("資源正在被使用");
//放大資源占用時間,便于觀察
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
semaphore.release(1);//釋放一個資源
System.out.println("-----------釋放資源包----------");
}
return "Success";
}
}
運作的結果圖(以極快的手速一起調用接口進行通路):

簡單解析:
我在代碼裡面設定的可用的資源包是:
//定義資源包的總數 隻有2個
Semaphore semaphore=new Semaphore(2);
//設定這個接口可用的資源數
int availablePermits=semaphore.availablePermits();
然後這個整體的運作流程就是這樣:
一個請求調用接口,那麼就會先去判斷資源包還有沒有?
如果有,那就搶;搶到了,就開始使用!且,此刻可用的總資源包就-1 :
//請求占用一個資源
semaphore.acquire(1);
如果沒有,那就直接傳回了提示,就是說資源緊張~
然後在搶到資源包開始使用的時候,我們可以看到控制台輸出了一下,資源正在被使用,顧名思義(就是說有人在使用咯,當然你可以擴充,作為日志跟蹤,我之前的部落格有介紹怎麼擷取請求者的IP位址也有怎麼生成日志等等)
然後在使用完畢的時候,就釋放資源包,
//釋放一個資源
semaphore.release(1);
那麼如果剛好這時候有請求過來了,那就可以申請使用資源包了。
結合我的運作結果: