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
然后退出。注意:如果任何线程仍在运行,程序将不会退出。