网上类似文章很多,不多说,直接上代码:
- /**
- * 流控类(Semaphore实现)
- *
- * @author ln
- *
- */
- public class FlowControl {
- /**
- * 最大访问量
- */
- private static final int MAX_ACCESS_COUNT = 20;
- /**
- * 只能有MAX_ACCESS_COUNT个线程数同时访问
- */
- private static final Semaphore semaphore = new Semaphore(MAX_ACCESS_COUNT);
- public static void main(String[] args) {
- // 线程池
- ExecutorService exec = Executors.newCachedThreadPool();
- // 模拟30个客户端
- for (int i = 0; i < 30; i++) {
- Runnable run = new Runnable() {
- @Override
- public void run() {
- try {
- // 1秒钟内得不到许可,则丢弃访问。
- if (semaphore.tryAcquire(1, TimeUnit.SECONDS)) {
- System.out.println("正在执行...");
- //做一些事情...
- Thread.sleep(2 * 1000);
- System.out.println("执行完毕!");
- } else {
- System.out.println("访问被拒绝!!!");
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } finally {
- // 执行完成,释放许可。
- semaphore.release();
- }
- }
- };
- exec.execute(run);
- }
- // 关闭线程池
- exec.shutdown();
- }
- }
转自 : https://blog.youkuaiyun.com/hyxhbj1/article/details/72847048