【发布时间】: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