java - 为java threadPool中的每个线程设置超时

标签 java multithreading threadpool executorservice

我想为线程池中执行的每个线程(非 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
......

最佳答案

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

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

关于java - 为java threadPool中的每个线程设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767477/

相关文章:

java.net.ConnectException : Connection timed out while connecting through a proxy 异常

java - Avro 解码给出 java.io.EOFException

Java 串流时声音不是很清楚

java - 在 RESTful Web 服务中使用 GET、PUT 和 DELETE HTTP 方法

java - 并行编程 2 个线程运行共享变量

java - 为什么将 Thread.currentThread().isInterrupted() 与 try/catch 一起使用

c++ - 如何在 Boost/C++ 实现中控制线程池

java - 关于 100 个任务的线程创建或线程池

python - Apache 和 Python 线程处理奇怪的结果

java - 修复了线程池和运行线程时的异常