zoukankan      html  css  js  c++  java
  • java并发--流量控制demo

    实现一个流控程序。控制客户端每秒调用某个远程服务不超过N次,客户端是会多线程并发调用,需要一个轻量简洁的实现,大家看看下面的一个实现,然后可以自己写一个实现。

    import java.util.Date;
    
    import java.util.concurrent.ExecutorService;
    
    import java.util.concurrent.Executors;
    
    import java.util.concurrent.Semaphore;
    
    import java.util.concurrent.TimeUnit;
    
    public class Test {
    
        final static int MAX_QPS = 10;
    
        final static Semaphore semaphore = new Semaphore(MAX_QPS);
    
        public static void main (String ... args) throws Exception {
    
            Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
    
                @Override
    
                public void run() {
    
                    semaphore.release(MAX_QPS/2);
    
                }
    
            }, 1000, 500, TimeUnit.MILLISECONDS);
    
            //lots of concurrent calls:100 * 1000
            ExecutorService pool = Executors.newFixedThreadPool(100);
    
            for (int i=100;i>0;i--) {
    
                final int x = i;
    
                pool.submit(new Runnable() {
    
                    @Override
    
                    public void run() {
    
                        for (int j=1000;j>0;j--) {
    
                            semaphore.acquireUninterruptibly(1);
                            remoteCall(x, j);
    
                        }
    
                    }
    
                });
    
            }
    
            pool.shutdown();
    
            pool.awaitTermination(1, TimeUnit.HOURS);
    
            System.out.println("DONE");
        }
    
        private static void remoteCall(int i, int j) {
            System.out.println(String.format("%s - %s: %d %d",new Date(),
                Thread.currentThread(), i, j));
        }
    
    }
  • 相关阅读:
    dblink
    linux 查进程、杀进程、起进程
    oracle 资源统计SQL语句
    DIV+CSS+javascript 手动轮播图
    接受同步数据接口
    java String StringBuffer StringBuilder
    SpringMVC Servlet 分页查询接收参数
    WPF 开发
    收集整理的各地精品青年旅舍大全(
    Linux平台Java调用so库JNI使用例子
  • 原文地址:https://www.cnblogs.com/maohuidong/p/7865916.html
Copyright © 2011-2022 走看看