Demand background: because of the frequent to creating and destroying threads is the consumption of resources, the number of concurrent threads and difficult to control, so the team need to write a function of the thread pool, to manage the life cycle of a thread by oneself, and root according to busy degree of thread pool of threads in the pool for dynamic expansion, Now project manager abstracts the thread pool object contains several major features (1) can be expansion and thread count, according to the number of tasks in your spare time only save coreSize number of threads in thread pool, and when coreSize threads have all at work, at this time if we add tasks to come in, will be a new thread, accept the task, until the number of threads in the pool is achieved when maxSize, not in the new thread (2) when the number of threads to maxSize, and all threads in a work state, if there are tasks added to come at this moment, it is stored in a Queue (can customize the Queue, can also be used on its own research and existing in the JDK Queue subclass) 3. If the number of tasks in the Queue have reached the maximum value (the Queue is full), have added to come over, at this time, discarding the strategy execution (can do nothing, also can still abnormal, it can also be called directly to the main thread run disposal, etc., it is best to use the strategy pattern rather than the if - else) 4. Define a thread of free time, if the thread pool finished processing tasks, thread idle, according to the defined new threads of free time, if time Reached, recycling threads until the number of threads to achieve coreSize number for check, (pay attention to recycling operations such as atomic, prevent data inconsistency)
Ideas, allow to complete all functions in a class, then to face to the object code refactoring can directly read the JDK thread pool source code, reference to write a can (suggest) write a test class, test your thread pool is functioning normally
CodePudding user response:
His handwriting is too time consuming, the ExecutorService threadPool=Executors. NewCachedThreadPool () can understand, and you need some similar
CodePudding user response:
You can see the JDK source code, and then in one way or another
CodePudding user response:
Suggest you look at the current mainstream technology of the source code, this first, and then in this way, then it went,