版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/qq_18860653/article/details/83584349
通过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();
}
}