1, is it better to create as many threads as possible?
When a program creates a large number of threads, the active thread consumes memory. If the number of threads that can be run is greater than the number of available processors, some threads will be idle. A large number of idle threads can consume a lot of memory, put pressure on garbage collection, and many threads will incur additional performance overhead when competing for CPU resources.
2, a bounded container can be implemented through the semaphore mechanism (Semaphore)
The count semaphore is used to control the number of operations that access a particular resource at the same time. For example, when new is a hashset, its Add method can be called to continually add elements to the HashSet, but the number of elements added to HashSet can be limited by the semaphore mechanism. Call Semaphore.acquire () each time an element is added, delete the element and call Semaphore.release ()
This bounded queue can also prevent high-load applications from running out of memory.
3, the thread pool simplifies the work of threading management, and Java.util.concurrent provides a flexible thread pooling implementation as part of the executor framework. The executor interface provides a standard way to decouple the submission process and execution of a task, and to represent tasks with runnable. Executor based on the producer-consumer model, the task is submitted as the producer, and the thread performing the task is the equivalent of the consumer.
4, performing tasks in the thread pool is more advantageous than assigning a thread to each task: By reusing an existing thread instead of creating a new thread, you can allocate the overhead incurred during thread creation and destruction while processing multiple requests, and second, when the request arrives, the worker thread passes through the already existing Therefore, it is not possible to delay the execution of a task due to waiting for the creation of the thread, thereby improving responsiveness; creating the right number of threads in the thread pool keeps the CPU busy, preventing multiple threads from competing with each other to make the application run out of memory or fail.
Both 5,runnable and callable describe abstract computational tasks. These tasks are scoped, that is, there is a definite starting point, and eventually it will end. The tasks performed by Executor have 4 Life cycle phases: Create, submit, start, complete. Because some tasks may take a long time to perform, you typically want to be able to cancel those tasks. In the executor framework, tasks that have been committed but not yet started can be canceled, but for tasks that have already started, they can only be canceled if they are able to respond to interrupts. Canceling a completed task has no effect.
Basic concepts of JAVA concurrent Programming Learning (2)