Restricting thread count and Java concurrency

后端 未结 4 478
北海茫月
北海茫月 2021-01-14 06:51

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

I plan to use threads to process items from an open queue w

4条回答
  •  借酒劲吻你
    2021-01-14 07:40

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

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

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

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

    ExecutorService threadPool = Executors.newFixedThreadPool(10);
    

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

    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

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

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

    I hope this helps you to solve your problem.

提交回复
热议问题