Java 使用 executorservice 多线程执行作业?
Java job execution multithreaded with executorservice?
如何实现这样的功能?
我有一个动态队列,它在未知时间被必须执行的可运行对象填满。 ExecutorService 应该只启动有限数量的线程,当达到最大线程大小时,它应该停止执行更多的线程,直到一个线程完成,然后执行下一个任务。
到目前为止我遇到了这个:
ExecutorService executor = new ThreadPoolExecutor(20, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
databaseConnectionQueue);
ExecutorService 在队列填满之前创建,并且在队列被删除之前应该保持活动状态,而不是在队列为空时,因为这可能会发生。有人可以帮我吗?
ThreadPoolExecutor
为空时不会关机。来自 JavaDoc:
A pool that is no longer referenced in a program AND has no remaining
threads will be shutdown automatically.
我相信你应该使用 FixedThreadPool (Executors.newFixedThreadPool)
根据 javadoc [Executors.newFixedThreadPool]
Creates a thread pool that reuses a fixed number of threads operating
off a shared unbounded queue. At any point, at most nThreads threads
will be active processing tasks. If additional tasks are submitted
when all threads are active, they will wait in the queue until a
thread is available. If any thread terminates due to a failure during
execution prior to shutdown, a new one will take its place if needed
to execute subsequent tasks. The threads in the pool will exist until
it is explicitly shutdown.
希望对您有所帮助。谢谢
如何实现这样的功能?
我有一个动态队列,它在未知时间被必须执行的可运行对象填满。 ExecutorService 应该只启动有限数量的线程,当达到最大线程大小时,它应该停止执行更多的线程,直到一个线程完成,然后执行下一个任务。
到目前为止我遇到了这个:
ExecutorService executor = new ThreadPoolExecutor(20, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
databaseConnectionQueue);
ExecutorService 在队列填满之前创建,并且在队列被删除之前应该保持活动状态,而不是在队列为空时,因为这可能会发生。有人可以帮我吗?
ThreadPoolExecutor
为空时不会关机。来自 JavaDoc:
A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically.
我相信你应该使用 FixedThreadPool (Executors.newFixedThreadPool)
根据 javadoc [Executors.newFixedThreadPool]
Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.
希望对您有所帮助。谢谢