限制线程计数和Java并发

编程入门 行业动态 更新时间:2024-10-26 02:32:59
本文介绍了限制线程计数和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: docs.oracle/javase/6/docs/api/java/util/concurrent/ExecutorService.html

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

执行者: docs.oracle /javase/6/docs/api/java/util/concurrent/Executors.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.

这是一个非常小的教程: www.math.uni-hamburg.de/doc/java/tutorial/essential/threads/group.html

This is a very small tutorial : 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.

未来: docs.oracle/javase/6 /docs/api/java/util/concurrent/Future.html

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

I hope this helps you to solve your problem.

更多推荐

限制线程计数和Java并发

本文发布于:2023-11-06 09:45:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563349.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!