Java 訊號量 Semaphore使用方法詳解

來源:互聯網
上載者:User


在用Semaphore 訊號量的時候,感覺對公平調度比較有用,可以控制多線程爭奪資源時候,最大可以幾個在執行,隨手寫了代碼測試下,如下:

說明:

1. acquire() 擷取一個許可,如果沒有就等待
2. release() 釋放一個許可
3. Semaphore可以控制某個資源可被同時訪問的個數,自行初始化的數量,為1當然就順序執行了


package com.i5a6.semp.test;
 
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
 
public class SemaphoreTest {
 
 private Semaphore semp;
 
 private ExecutorService executorPool;
 
 public SemaphoreTest(int threadNum) {
  semp = new Semaphore(threadNum);
  executorPool = Executors.newFixedThreadPool(threadNum);
 }
 
 public void doEnd() {
  this.executorPool.shutdown();
 }
 
 public void doMsg(int num) {
  try {
   semp.acquire();
   executorPool.execute(new HelloUExecutor(num));
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 
 class HelloUExecutor implements Runnable {
  private int num;
 
  public HelloUExecutor(int num) {
   this.num = num;
  }
 
  Random r = new Random();
 
  @Override
  public void run() {
   try {
    System.out.println(num);
    Thread.sleep(r.nextInt(1000));
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    semp.release();
   }
  }
 }
 
 public static void main(String[] args) {
  // 初始化為1 順序執行
  SemaphoreTest st = new SemaphoreTest(5);
  for (int i = 0; i < 20; i++) {
   st.doMsg(i);
  }
  st.doEnd();
 }
 
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.