问题
What are the types of thread pools in java. I need to implement a robust multi-threaded application which uses heavy computation, which thread pool should I use?
回答1:
There are various thread pools in java:
Single Thread Executor : A thread pool with only one thread. So all the submitted tasks will be executed sequentially. Method :
Executors.newSingleThreadExecutor()
Cached Thread Pool : A thread pool that creates as many threads it needs to execute the task in parrallel. The old available threads will be reused for the new tasks. If a thread is not used during 60 seconds, it will be terminated and removed from the pool. Method :
Executors.newCachedThreadPool()
Fixed Thread Pool : A thread pool with a fixed number of threads. If a thread is not available for the task, the task is put in queue waiting for an other task to ends. Method :
Executors.newFixedThreadPool()
Scheduled Thread Pool : A thread pool made to schedule future task. Method :
Executors.newScheduledThreadPool()
Single Thread Scheduled Pool : A thread pool with only one thread to schedule future task. Method :
Executors.newSingleThreadScheduledExecutor()
回答2:
There are many types ;)
There is, for instance, ExecutorService. This is the "basic" implementation which allows to submit tasks etc. You will probably want to use Executors to obtain a new one, since it has static factory methods for the most common scenarios.
Since Java 7 you also have ForkJoinPool.
Also have a look at FutureTask, since this is a very convenient class to build individual threads.
回答3:
Take a look at Executors.
Each common ExecutorService
is explained and you will probably find one that fits your needs among them.
回答4:
You can read more about ThreadPoolExecutors here: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
However, it might be a good idea to look at the ForkJoinTask API: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinTask.html
回答5:
This shows good animations on the diffrent concurrency constructs, may this will help you choose
http://sourceforge.net/projects/javaconcurrenta/
来源:https://stackoverflow.com/questions/17186206/types-of-thread-pools-in-java