1. 程式人生 > >[閉鎖]同步工具類 Semaphore 的使用

[閉鎖]同步工具類 Semaphore 的使用

通過Semaphore控制流量

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


/**
 * 通過Semaphore控制流量
 *
 * @author yuyufeng
 * @date 2018/10/31.
 */
public class SemaphoreTest {
    //初始化執行緒池 大小為 10
    private static ExecutorService threadPool = Executors.newFixedThreadPool(10);
    //通過Semaphore控制流量,最多允許5個同時執行
    private static Semaphore semaphore = new Semaphore(5);


    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println("doSomething...");
                        TimeUnit.SECONDS.sleep(2);
                        semaphore.release();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
}