简体   繁体   中英

Difference between Thread and Threadpool

Can any one guide me with example about Thread and ThreadPool what is difference between them? which is best to use...? what are the drawback on its

Since a thread can only run once, you'd have to use a thread per task. However, creating and starting threads is somewhat expensive and can lead to a situation where too many threads are waiting for execution (don't remember the exact name for this right now) - which further reduces performance.

A thread pool is - as the name suggests - a pool of worker threads which are always running. Those threads then normally take tasks from a list, execute them, then try to take the next task. If there's no task, the thread will wait.

Using a thread pool has several advantages:

  • you don't have to create a thread per task
  • you normally have the optimal number of threads for your system (depending on the JVM too)
  • you can concentrate on writing tasks and use the thread pool to manage the infrastructure

Edit: Here are some quite good articles on concurrency in general: Sutter's Mill , look at the bottom for more links. Although they're primarily written for C/C++ the general concepts are the same, since it also describes the interdependence between concurrency solutions and hardware. A good article to understand concurrency performance issues is this article on drdobbs.com .

A thread pool is a collection of threads which are assigned to perform uniformed tasks. The advantages of using thread pool pattern is that you can define how many threads is allowed to execute simultaneously. This is to avoid server crashing due to high CPU load or out of memory condition, eg the server's hardware capacity can support up to 100 requests per second only.

Database pooling has the similar concept with thread pool.

This pattern is widely used in most of the back-end servers' application process.

While a thread, is a unit which execute a task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM