1. 程式人生 > >控制併發訪問的執行緒數 Semaphore 訊號燈

控制併發訪問的執行緒數 Semaphore 訊號燈

 
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/*
 * Semaphore: 控制併發訪問的執行緒數
 */
public class SemaphoreTest {
	public static void main(String[] args) {
		ExecutorService executorService = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(3);//訊號 燈,有3個許可,只能有3個併發執行緒
		
		for (int i = 0; i < 10; i++) {
			executorService.submit(new Runnable() {
				public void run() {
					try {
						semaphore.acquire();//獲取許可,沒有許可的,只能等待
						System.out.println("執行緒" + Thread.currentThread().getName() + 
								"進入,當前已有" + (3 - semaphore.availablePermits())
								+ "執行緒併發.");
						Thread.sleep((long) (Math.random() * 5000));
						System.out.println("執行緒" + Thread.currentThread().getName()
								+ "即將離開.");
						semaphore.release();
						System.out.println("執行緒" + Thread.currentThread().getName()
								+ "已離開,當前還有"+ (3 - semaphore.availablePermits())
								+ "執行緒併發.");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 	
				}
			});
		}
		executorService.shutdown();
	}