我对我使用ScheduledExecutorService的新实现感到好奇,在这个实现中,任务预计将在100ms周期和0ms延迟内完成。但是,如果有系统负载并且占用时间为550ms,是否会有一个由ScheduledExecutorService维护的队列来处理这4个挂起的任务?然后在(0ms延迟)第一个完成后立即运行。如果第二次执行需要560毫秒,会不会再增加4个线程到队列中呢?
没有关于这方面的文档,否则我可能会忽略它。但我希望确保这样的执行堆积起来会引发泄漏或溢出。
例如:下面的代码,主线程会失败吗?
private static ScheduledExecutorService consumerThreadPool = Executors.newSingleThreadScheduledExecutor();
public static void main(String[] args) throws Exception {
consumerThreadPool.scheduleAtFixedRate(() -> performTask(), 0, 1, TimeUnit.MILLISECONDS);
}
private static void performTask () {
try {
Thread.sleep(550);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}发布于 2020-06-20 17:01:49
如果你的任务超出了下一个计划时间,你的任务将被跳过,你可以很容易地用System.out.println进行验证,并将睡眠时间从500ms改为5000ms:
public static void main(final String[] args) throws InterruptedException, ExecutionException
{
var executor = Executors.newScheduledThreadPool(1);
var count = new AtomicInteger();
Runnable task = () -> {
String desc = "run("+((System.currentTimeMillis() / 1000) % 60)+") "+Thread.currentThread().getName()+" count "+count.incrementAndGet();
System.out.println(desc);
if(count.get() == 50)
throw new RuntimeException("I give up!");
try
{
Thread.sleep(2500);
}
catch (InterruptedException e)
{
System.out.println("Thread "+Thread.currentThread().getName()+" INTERRUPTED");
}
};
var future = executor.scheduleAtFixedRate(task, 5000, 1000, TimeUnit.MILLISECONDS);
System.out.println("Calling future.get() ...");
try {
var res = future.get();
System.out.println("future.get()="+res);
}
catch(Exception e)
{
System.err.println("There was an exception:" +e);
// Decide between "continue" or "throw e" here
// ...
}
executor.shutdownNow();
System.out.println("shutdown complete");
}https://stackoverflow.com/questions/62477008
复制相似问题