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