Limit threads and Java concurrency

I can't find an example of this particular case using the latest Java Concurrent routines

I plan to use threads to process items from an open queue, which may contain 0 to thousands of requests I want to limit so that no less than 0 and no more than 10 threads process queue entries at any given time

Is there a Java Concurrent Process for this particular type of case?

Solution

I think thread pool is what you are looking for Look at executorservice and executors

ExecutorService: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

Executor: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html

Gets a new thread fixed thread pool that processes the maximum value 10 threads:

ExecutorService threadPool = Executors.newFixedThreadPool(10);

Using the commit method, you can pass callables or runnables to the pool

For your use case, you need a process to view the queue. If there is a new request, you must create a callable or runnable and pass it to the thread pool The swimming pool ensures maximum Execute 10 threads at a time

This is a very small tutorial: http://www.math.uni-hamburg.de/doc/java/tutorial/essential/threads/group.html

One advantage of using thread pool is that the submit method returns a future object, which supports the return type of the executing thread

future: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html

I hope this will help you solve the problem

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>