简体   繁体   English

Java作业执行与executorservice多线程?

[英]Java job execution multithreaded with executorservice?

How to i implement such a function ? 我如何实现这样的功能?

I have a dynamic queue which gets filled at unknown times with runnables, which have to be executed. 我有一个动态队列,该队列在未知时间被必须执行的可运行对象填充。 The ExecutorService should only start a limited amount of threads, when the maximum thread size is reached, it should stop executing more threads, until one thread finishes, then the next task should be executed. ExecutorService应该仅启动有限数量的线程,当达到最大线程大小时,它应该停止执行更多线程,直到一个线程完成,然后应执行下一个任务。

So far i came across this: 到目前为止,我遇到了这个问题:

ExecutorService executor = new ThreadPoolExecutor(20, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                databaseConnectionQueue);

The ExecutorService is created before the queue is filled, and should stay alive until the queue is deleted, not when its empty, because this can happen. ExecutorService是在队列填充之前创建的,并且应保持活动状态直到队列被删除为止,而不是在队列为空之前,因为这可能发生。 Can anybody help me ? 有谁能够帮助我 ?

ThreadPoolExecutor will will not shutdown when it is empty. ThreadPoolExecutor为空时将不会关闭。 From the JavaDoc : JavaDoc

A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. 程序中不再引用且没有剩余线程的池将自动关闭。

I believe you should use FixedThreadPool (Executors.newFixedThreadPool) 我相信您应该使用FixedThreadPool(Executors.newFixedThreadPool)

As per javadoc [ 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. 在任何时候,最多nThreads个线程都是活动的处理任务。 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. 池中的线程将一直存在,直到明确将其关闭。

Hope it helps. 希望能帮助到你。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM