线程池实现
A thread is an independent program’s path of execution. In java, each thread extends the java.lang.Thread class or implements java.lang.Runnable.
Multithreading refers to the execution of two or more threads concurrently within a single task.In multithreading, each task can have many threads, and these threads can run concurrently, either asynchronously or synchronously. You can find more information about thread and multithreading in another tutorial that I wrote about multithreading here.
1. What is Thread pool
It is important to use synchronise block while working with the queue, to control the access of threads to the queue.
In the above example, we used
instead of . Because has more desirable performance characteristics than ; in particular, causes many fewer context switches, which is important in a server application. But it is important to make sure when using in other situation as there are subtle risks associated with using , and it is only appropriate to use it under certain specific conditions.The following figure demonstrates the thread pool design in the above example.
2. Effective use of thread pools
Thread pool is a powerful mechanism for structuring multithreaded applications, but it is not without risk. Applications built with thread pools could have all the same concurrency risks as any other multithreaded applications, such as deadlock, resource thrashing, synchronization or concurrency errors, thread leakage and request overload.
Here are some points:
- Do not queue tasks which wait synchronously for other tasks as this can cause a deadlock.
- If the task requires to wait for a resource such as I/O, specify a maximum wait time and then fail or requeue the task execution. This guarantees that some progress will be made by freeing the thread for another task that might complete successfully.
- Tune the thread pool size effectively, and understand that having too few threads or too many threads both can cause problems. The optimum size of a thread pool depends on the number of available processors and the nature of the tasks on the work queue.
3. Conclusion
The thread pool is useful for organizing server applications and it is really important to implement it properly to prevent any issues such as deadlock and complexity of usage for
or . So, it is recommended to consider using one of the classes from , such as , rather than writing thread pool from scratch. If the requirement is to create threads to handle short-lived tasks, you could consider using a thread pool instead.4. Download the Source Code
This was a tutorial for thread pool, to download the source code, click here.
转自:https://www.javacodegeeks.com/2016/12/implement-thread-pool-java.html
其它相关文章http://blog.****.net/w2393040183/article/details/52177572