1. 程式人生 > >Java執行緒同步工具-Semaphore

Java執行緒同步工具-Semaphore

Semaphore:訊號燈

特點:控制每次執行的執行緒數,達到控制執行緒併發的效果

  • 測試程式碼
package com.zhiwei.thread;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 訊號燈:當執行緒空閒時自動去執行阻塞的執行緒,實現執行最優化
 */
public class SemaphoreTest {

	public static void main(String[] args) {

		ExecutorService threadPool = Executors.newCachedThreadPool();
		Semaphore sp = new Semaphore(3); // 定義訊號燈,一次最多能處理3個執行緒

		for (int i = 0; i <= 20; i++) {
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
                        Thread.sleep(new Random().nextInt(5000));						
						
						sp.acquire(); // 獲取訊號,訊號燈處理阻塞執行緒,最多允許3個執行緒訪問
						System.out.println(Thread.currentThread().getName() + ":進入訊號燈,還有" +  sp.availablePermits() + "個訊號");
						
						Thread.sleep(new Random().nextInt(2000));
						
						sp.release();// 回收訊號燈訊號,供別的執行緒使用
						System.out.println(Thread.currentThread().getName() + ":離開訊號燈,還有" +  sp.availablePermits() + "個訊號");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}

		threadPool.shutdown();
	}
}

  • 效果
    這裡寫圖片描述
分析:列印日誌可以看出最多隻有3個執行緒併發執行