Semaphore使用方法


一個計數信號量。從概念上講,信號量維護了一個許可集。如有必要,在許可可用前會阻塞每一個 acquire(),然后再獲取該許可。每個 release() 添加一個許可,從而可能釋放一個正在阻塞的獲取者。但是,不使用實際的許可對象,Semaphore 只對可用許可的號碼進行計數,並采取相應的行動。

構造方法:
Semaphore(int permits)
創建具有給定的許可數和非公平的公平設置的 Semaphore。
Semaphore(int permits, boolean fair)
創建具有給定的許可數和給定的公平設置的 Semaphore。
主要方法:
release(int permits)
釋放給定數目的許可,將其返回到信號量。
acquire()
從此信號量獲取一個許可,在提供一個許可前一直將線程阻塞,否則線程被中斷。
示列1:
線程1會先執行完,然后釋放兩個線程
線程2和線程3會阻塞知道線程1執行release語句

Semaphore sph = new Semaphore(0); // 初始化釋放幾個線程
		
		ExecutorService pool = new ThreadPoolExecutor(3, 3, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
		pool.execute(new Thread() {
			@Override
			public void run() {
				
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				print();
				sph.release(2);
			}
		});
		
		pool.execute(new Thread() {
			@Override
			public void run() {
				try {
					sph.acquire();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				print();
			}
		});
		
		pool.execute(new Thread() {
			@Override
			public void run() {
				try {
					sph.acquire();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				print();
			}
		});		
	}
	
	private static void print() {
		for (int i = 0; i < 10; i++) {
			System.out.println(Thread.currentThread().toString() + "*" + i);
		}
	}

示例2:控制一個方法最大同時線程訪問數

public class SemaphoreTest {

	 static Semaphore semaphore = new Semaphore(5,true); // 最大線程數
	 public static void main(String[] args) {
		 for(int i=0;i<100;i++){
			 new Thread(new Runnable() {
	
		 @Override
		 public void run() {
			 test();
		 }
			 }).start();
		 }
	
	 }
	
	 public static void test(){
		 try {
		 //申請一個請求
			 semaphore.acquire(); // 如果線程超過5個,其他線程會阻塞到這來,知道線程執行結束釋放許可
		} catch (InterruptedException e1) {
				e1.printStackTrace();
		 }
		System.out.println(Thread.currentThread().getName()+"進來了");
		 try {
			 Thread.sleep(1000);
		 } catch (InterruptedException e) {
			 e.printStackTrace();
		}
		 System.out.println(Thread.currentThread().getName()+"走了");
		 //釋放一個請求
		 semaphore.release();
	 }
 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM