1. 程式人生 > 其它 >java併發:執行緒同步機制之Semaphore

java併發:執行緒同步機制之Semaphore

一、初識Semaphore

小結:

A、可以將訊號量視覺化為一個計數器,它可以遞增或遞減。

B、從概念上講,訊號量維護了一個許可集合,Semaphore對可用的許可進行計數。

C、當計數器的值為0時,它能夠使執行緒等待。

二、示例

The three steps you must follow when you use a semaphore to implement a critical section and protect the access to a shared resource:

  • First, you acquire the semaphore, with the acquire() method.
  • Then, you do the necessary operations with the shared resource.
  • Finally, release the semaphore with the release() method.

場景:

假設一個伺服器資源有限,任意某一時刻只允許3個人同時訪問,這時一共來了10個人

package com.test;

import java.util.concurrent.Semaphore;

public class SemaphoreDemo{
    
    public static void main(String args[]) throws
Exception{ final Semaphore semaphore = new Semaphore(3);//一次只允許3個人進行訪問 for(int i=0;i<10;i++) { final int no = i; Runnable thread = new Runnable() { public void run (){ try { System.out.println(
"使用者"+no+"連線上了:"); Thread.sleep(300L); semaphore.acquire();//獲取執行的許可 System.out.println("使用者"+no+"開始訪問後臺程式..."); Thread.sleep(1000L);//模仿使用者訪問服務過程 semaphore.release();//釋放,允許下一個執行緒訪問後臺 System.out.println("使用者"+no+"訪問結束。"); } catch (InterruptedException e) { e.printStackTrace(); } } }; new Thread(thread).start(); } System.out.println("Main thread end!"); } }

上述程式碼執行結果如下:

使用者1連線上了:
使用者3連線上了:
使用者4連線上了:
使用者2連線上了:
使用者0連線上了:
使用者5連線上了:
使用者7連線上了:
Main thread end!
使用者6連線上了:
使用者8連線上了:
使用者9連線上了:
使用者3開始訪問後臺程式...
使用者4開始訪問後臺程式...
使用者2開始訪問後臺程式...
使用者4訪問結束。
使用者3訪問結束。
使用者7開始訪問後臺程式...
使用者0開始訪問後臺程式...
使用者8開始訪問後臺程式...
使用者2訪問結束。
使用者5開始訪問後臺程式...
使用者0訪問結束。
使用者7訪問結束。
使用者1開始訪問後臺程式...
使用者8訪問結束。
使用者6開始訪問後臺程式...
使用者1訪問結束。
使用者9開始訪問後臺程式...
使用者5訪問結束。
使用者6訪問結束。
使用者9訪問結束。

從結果上可以看出來,10個人同時進來,但是隻能同時3個人訪問資源,釋放一個允許進來一個

Note:

When a thread has finished the use of the shared resource, it must release the semaphore so that the other threads can access the shared resource.

That operation increases the internal counter of the semaphore.

三、詳解Semaphore

四、參考資料

(1)https://howtodoinjava.com/java/multi-threading/binary-semaphore-tutorial-and-example/

(2)https://howtodoinjava.com/java/multi-threading/control-concurrent-access-to-multiple-copies-of-a-resource-using-semaphore/