如何控制某個方法允許併發訪問線程的個數?
1 package com.soyoungboy; 2 3 import java.util.concurrent.Semaphore; 4 /** 5 * 6 * @author soyoungboy 2017年1月25日15:51:15 7 * 8 */ 9 public class SemaphoreTest { 10 static Semaphore semaphore = new Semaphore(5,true); 11 public static void main(String[] args) { 12 for(int i=0;i<100;i++){ 13 new Thread(new Runnable() { 14 15 @Override 16 public void run() { 17 test(); 18 } 19 }).start(); 20 } 21 22 } 23 24 public static void test(){ 25 try { 26 //申請一個請求 27 semaphore.acquire(); 28 } catch (InterruptedException e1) { 29 e1.printStackTrace(); 30 } 31 System.out.println(Thread.currentThread().getName()+"進來了"); 32 try { 33 Thread.sleep(1000); 34 } catch (InterruptedException e) { 35 e.printStackTrace(); 36 } 37 System.out.println(Thread.currentThread().getName()+"走了"); 38 //釋放一個請求 39 semaphore.release(); 40 } 41 }
構造函數創建了一個 Semaphore 對象,並且初始化了 5 個信號。這樣的效果是控件 test 方法最多只能有 5 個線程併發訪問,對於 5 個線程時就排隊等待,走一個來一下;
請求一個信號(消費一個信號),如果信號被用完了則等待;
釋放一個信號,釋放的信號新的線程就可以使用了.