Introduction
The rational use of the thread pool can bring three benefits. First: Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created. Second: Reduce the wait for the response time of the system for the external service. Third: Improve the manageability of threads. Threads are scarce resources, and if created indefinitely, the system memory is consumed, so the concept of referencing to the thread pool is used.
Thread pooling The main idea is to understand a method.
Understanding several parameters
Corepoolsize (basic size of the thread pool): When a task is submitted to the thread pool, the line pool creates a thread to perform the task, and the thread is created even if other idle basic threads are able to perform new tasks, and is no longer created until the number of tasks that need to be executed is larger than the thread pool base size. If the thread pool's Prestartallcorethreads method is called, the thread pool creates and starts all basic threads in advance.
Runnabletaskqueue (Task queue): A blocking queue that is used to hold tasks waiting to be executed. You can select the following blocking queues.
Arrayblockingqueue: is a bounded blocking queue based on the array structure, which sorts the elements in FIFO (first-out) principle.
Linkedblockingqueue: A blocking queue based on a linked list structure, which sorts elements in FIFO (first-out), with throughput typically higher than arrayblockingqueue. The static Factory Method Executors.newfixedthreadpool () uses this queue.
Synchronousqueue: A blocking queue that does not store elements. Each insert operation must wait for another thread to invoke the remove operation, or the insert operation will always be in a blocked state, with throughput typically higher than linkedblockingqueue, and the static factory method Executors.newcachedthreadpool Use this queue.
Priorityblockingqueue: An infinite blocking queue with priority.
Maximumpoolsize (maximum thread pool size): The maximum number of threads allowed to be created by a thread pool. If the queue is full and the number of threads that have been created is less than the maximum number of threads, the thread pool will then create new threads to perform the task. It is worth noting that if you use the unbounded task queue This parameter has little effect.
Threadfactory: Used to set the factory for creating threads, you can set a more meaningful name for each thread that is created through the thread factory, and it is very helpful to debug and locate problems.
Rejectedexecutionhandler (Saturation policy): When the queue and thread pool are full, indicating that the thread pools are saturated, a policy must be taken to handle the new tasks that are submitted. This policy is abortpolicy by default, indicating that an exception is thrown when a new task cannot be processed. The following are the four strategies provided by JDK1.5. N AbortPolicy: Throws an exception directly.
Callerrunspolicy: Runs the task only with the caller's thread.
Discardoldestpolicy: Discards the most recent task in the queue and executes the current task.
Discardpolicy: not processed, discarded.
It is also possible to implement the Rejectedexecutionhandler interface customization strategy According to the application scenario. Tasks such as logging or persistence that cannot be processed.
KeepAliveTime (thread activity hold time): When the worker thread of the thread pool is idle, the time to remain alive. So if the task is a lot, and each task executes a short time, you can adjust the time to increase the utilization of the thread.
Timeunit (unit of thread activity hold time): Optional units have day (days), hours (HOURS), minutes (MINUTES), milliseconds (MILLISECONDS), microseconds (microseconds, 1 per thousand milliseconds), and nanoseconds ( nanoseconds, 1 per thousand microseconds).
int righessize=rights.size (); Gets the number of times the data connection needs to be final Countdownlatch countdownlatch=new Countdownlatch (righessize); The concurrency tool is used to block waiting threads to perform Executorservice executorservice= executors.newcachedthreadpool ();//Use thread pool int Nthreads=runtime.getruntime (). Availableprocessors (); Gets the number of CPU cores of the machine final Semaphore semp = new Semaphore (nthreads); Limit the number of threads for (int i=0;i<righessize;i++) {final apprights info=rights.get (i); Runnable run = new Runnable () {//Start threading @Override public void Run () {try {//get permission to the thread pool (when there are idle threads) Semp.acquire (); } catch (Exception e) {e.printstacktrace (); } Business logic processing//for (apprights info:rights) {//Low efficiency Menucountvo vo = new Menucountvo (); Vo.setmenuid (Info.getmenuid ()); int notreadcount = 0; String Menucode = Info.getmenucode (); try {switch (menucode) {case "notice": Call Angel Jsonobject JSON = new Jsonobject (); Json.put ("Usercode", Usercode); Json.put ("source", "SFA"); Notreadcount = Infomationservice.getunreadinform (JSON); Break Case "Sfa_store_patrol": Notreadcount = Storepatrolservice.getnotleavestorenum (Usercode);//statistical store inspection of non-departure records Break Case "SFA_STORE_ORDER_MRG"://statistics of the non-reading angle mark of the store order, add by Deco 20171012 Notreadcount = s Toreorderservice.getcornernum (Usercode); Break }} catch (Exception e) {notreadcount = 0; E.printstacktrace (); } vo.setnotreadcount (Notreadcount); Menucountlist.add (VO); After the business logic is processed, release the thread and plug the Semp.release (); Countdownlatch.countdown (); } }; Executorservice.execute (run); } countdownlatch.await (); After all the execution is complete, return to new Jsonresult (Apicode.ok, boolean.true). Data ("Menucountlist", menucountlist); } default:new Jsonresult (apicode.exception, boolean.true); } Resources Java concurrency Programming combat. JDK1.8 source code.
Java thread pool executor use