gpt4 book ai didi

java - ExecutorService.shutdown。当任务队列变空时如何关闭执行器?

转载 作者:行者123 更新时间:2023-11-30 09:27:11 27 4
gpt4 key购买 nike

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main
{
public static void main(String[] args)
{
final ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable()
{
@Override
public void run()
{
for (int i = 0; i < 10; i++)
executor.execute(new Runnable()
{
@Override
public void run()
{
System.out.println("run");
}
});
}
});
executor.shutdown();
try
{
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

我得到RejectedExecutionException 因为在 shutdown 之后调用了内部 executor.execute。在这种情况下我如何等待执行者?

最佳答案

你必须知道什么时候没有更多的任务。这不是它可以为您猜测的东西。将关闭移动到第一个任务中,它将按您预期的方式运行。即,仅当您知道不会添加更多任务时才调用关闭。

另一种方法是使用

final ExecutorService executor = new ThreadPoolExecutor(0, 10, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

这不会关闭执行器,但会停止所有线程,您可以在不再需要时丢弃执行器。注意:如果您稍后添加更多任务,它将根据需要启动线程。

final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 100, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
for (int i = 0; i < 1000; i++)
executor.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
Thread.sleep(2);
return null;
}
});
while (executor.getQueue().size() > 0) {
System.out.println("Queue " + executor.getQueue().size() + ", Pool size " + executor.getPoolSize());
Thread.sleep(200);
}
executor.setCorePoolSize(0);
while (executor.getPoolSize() > 0) {
System.out.println("Pool size " + executor.getPoolSize());
Thread.sleep(200);
}
System.out.println("Pool size " + executor.getPoolSize());

打印

Queue 946, Pool size 10
Queue 32, Pool size 10
Pool size 10
Pool size 0

然后退出。注意:如果任何线程仍在运行,程序将不会退出。

关于java - ExecutorService.shutdown。当任务队列变空时如何关闭执行器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670785/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com