【问题标题】:Set timeout for each thread in a java threadPool [duplicate]为java threadPool中的每个线程设置超时[重复]
【发布时间】:2018-01-27 18:42:21
【问题描述】:

我想为在线程池中执行的每个线程(非 future.get(time,unit))设置超时。目前我有以下代码:

private static void rpcService() throws Exception{
    long s = System.currentTimeMillis();
    TimeUnit.MILLISECONDS.sleep(100);//
    long e = System.currentTimeMillis();
    if(e-s > 100){
        System.out.println((e-s) + " MILLISECONDS");
    }
}

public static void main(String[] args) throws Exception {
    ExecutorService service = Executors.newFixedThreadPool(500);
    while (true) {
        TimeUnit.MILLISECONDS.sleep(1);
        service.submit(new Runnable() {
            public void run() {
                try {
                    //the rpc timeout is 100 milliseconds
                    rpcService();
                } catch (Exception e) {}
            }
        });
    }
}

为什么输出如下:

139 MILLISECONDS
133 MILLISECONDS
129 MILLISECONDS
128 MILLISECONDS
127 MILLISECONDS
126 MILLISECONDS
125 MILLISECONDS
123 MILLISECONDS
122 MILLISECONDS
121 MILLISECONDS
151 MILLISECONDS
......

【问题讨论】:

  • 在当前时间的第一次调用和最后一次调用之间,除了 100 毫秒的睡眠之外,您的计算机上发生了很多事情。这些其他的东西是随时间变化的。

标签: java multithreading threadpool executorservice


【解决方案1】:

System.currentTimeMillis() 不是测量持续时间的准确方法。你应该更喜欢System.nanoTime()

除了sleep 所花费的时间之外,还有更多的事情发生,无论你拥有多少内核,你都有 500 个线程在竞争,所以会有相当多的上下文切换。如果您使用https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor(),您将非常接近睡眠时间。

【讨论】:

    【解决方案2】:

    因为Thread.sleep() 是:

    取决于系统计时器和调度程序的精度和准确性。

    这不是实时保证。

    【讨论】:

      猜你喜欢
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 2016-06-03
      • 2018-04-29
      • 2011-05-24
      相关资源
      最近更新 更多