javamultithreadingjava.util.concurrentthreadpoolexecutor

MultiThreading Vs ThreadPoolExecutor


I have used multithreading in many of the applications I wrote. While reading more I came across ThreadPoolExecutors. I couldn't differentiate between the two scenario-wise.

Still what I understand is I should use multithreading when I have a task I want to divide the task into multiple small tasks to utilize CPU and do the work faster. And use ThreadPoolExecutor when I have a set of tasks and each task can be run independently of the other.

Please correct me if I am wrong.


Solution

  • A ThreadPoolExecutor is just a high level API that enables you to run tasks in multiple threads while not having to deal with the low level Thread API. So it does not really make sense to differentiate between multithreading and ThreadPoolExecutor.

    There are many flavours of ThreadPoolExecutors, but most of them allow more than one thread to run in parallel. Typically, you would use an Executor Service and use the Executors factory.

    For example, a ExecutorService executor = Executors.newFixedThreadPool(10); will run the tasks you submit in 10 threads.