本文介绍了限制线程计数和Java并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到使用最新JAVA并发例程的此特定案例的示例。

I couldn't find an example of this specific case using the latest JAVA concurrent routines.

我计划使用线程来处理来自可能包含0到数千个请求的打开队列中的项目。我想限制所以在任何给定的时间有不少于0,不超过10个线程处理队列项。

I plan to use threads to process items from an open queue which may contain 0 to thousands requests. I want to restrict so at at any given time there be no less than 0 and no more than say 10 threads handling queue items.

有一个Java并发进程面向这个特定类型的case?

Is there a Java concurrent process geared towards this specific type of case?

推荐答案

我认为线程池是你正在寻找。查看ExecutorService和Executors。

I think a thread pool is what you are looking for. Take a look at ExecutorService and Executors.

ExecutorService:

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

执行者:

获取一个新的线程固定线程池, 10线程一次:

Getting a new Thread fixed thread-pool that processes max. 10 Thread at once :

ExecutorService threadPool = Executors.newFixedThreadPool(10);

使用submit方法将Callables或Runnables传递到池。

With the submit Method you pass Callables or Runnables to the Pool.

对于你的用例,你需要一个进程查看队列,如果有一个新的请求Callable或Runnable必须创建并传递到线程池。池确保最大。

For your use case you need a process that looks into the Queue, if there is a new request a Callable or Runnable has to be created and passed to the thread-pool. The pool ensures that max. 10 threads are executed at once.

这是一个非常小的教程:

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

使用线程池的一个好处是,submit方法返回一个Future对象,它支持执行线程的返回类型。

A nice thing working with thread-pools is that the submit method returns a Future object, which supports return types for the executed threads.

未来:

我希望这可以帮助您解决问题。

I hope this helps you to solve your problem.

这篇关于限制线程计数和Java并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:17